How to print Linux command output to a file?

Use the > operator:

rsync -v > log.txt

will write the output of the rsync command to a file named log.txt.

You can call your script and redirect "standard output" (AKA STDOUT) to a log file. Use '>>' to append to the log file or '>' to overwrite the log file. The file will be created (if permissions on it's directory allow) if it doesn't already exist. If the file already exists, make sure it is writeable by you (or whoever runs your script).

If you always append to the log file rather than write over it, it is good practice to make sure from the very beginning that something will "rotate" your log file, that is, move it to some other name and remove older log files. If the log file is unique to your script, you could have your script take care of log file rotation.

Usually, the preferred way is to call your script with STDOUT redirected, but there may be times when you want to do the redirecting within the script itself for one or more commands. You can add ">> logfile" after any statement in a shell script to append STDOUT of that command to logfile. You can change that to "2>&1 >> logfile" to append both "standard error" (AKA STDERR) and STDOUT to logfile. You don't usually want to have STDERR also go to the logfile as STDERR is usually used to notify whatever/whoever is running the script of a problem. But there are times and situations where you do want that. If you like, you can group commands in your script inside { and } and redirect STDOUT of the whole group at once by putting the redirection after that closing brace.

In addition to the above, if you are curious to see the output printed to the screen AND to a file for archiving/grepping/etc, you might want to "tee" the output. It's a great command and is named after the T pipe found in real-world plumbing, and works well for "sub-consoles" like mysql, etc.

The command is tee... here's an example copied from a user named "toydi":

To display and log the output from a command at the same time: ls -l | tee -a file.log In this example, it will display the directory listing output and as well, save the output into file.log. The option -a signals the command to append rather than overwrite the file.

Also, check the picture on wikipedia for a nice visualization on how tee works. I'd link to it, but I don't have enough "reputation points" to post more than 1 link, and I felt "toydi" deserved the link credit :)