How can I redirect the output of multiple commands at once?
Redirecting the standard output of a single command is as easy as:
Toggle line numbers
1 date > file
To redirect standard error:
Toggle line numbers
1 date 2> file
To redirect both:
Toggle line numbers
1 date > file 2>&1
or, a fancier way:
Toggle line numbers
1 # Bash only. Equivalent to date > file 2>&1 but non-portable.
2 date &> file
Redirecting an entire loop:
Toggle line numbers
1 for i in "${list[@]}"; do
2 echo "Now processing $i"
3 # more stuff here...
4 done > file 2>&1
However, this can become tedious if the output of many programs should be redirected. If all output of a script should go into a file (e.g. a log file), the exec command can be used:
Toggle line numbers
1 # redirect both standard output and standard error to "log.txt"
2 exec > log.txt 2>&1
3 # all output including stderr now goes into "log.txt"
(See FAQ 106 for more complex script logging techniques.)
Otherwise, command grouping helps:
In this example, the output of all commands within the curly braces is redirected to the file messages.log.
In-depth: Illustrated Tutorial