It is possible to redirect the output of a single command in Bash to a file using the > convention. For example, to redirect the STDOUT output to a file, use:
ls -l > myfile.txt
However sometimes it would be better to redirect all output from multiple commands to a single file. This can be used by modifying the file descriptor, 1. First, we save a backup of the file handle for STDOUT and then change it to point to the desired file. We can then later restore STDOUT from the backup:
1 2 3 4 5 6 |
exec 6>&1 # Link file descriptor #6 with stdout (saves STDOUT) exec > myfile.txt # stdout replaced with file echo "this will be outputted to myfile.txt instead of the console (STDOUT)" exec 1>&6 6>&- # Restore stdout and close file descriptor #6. |
This can be very useful for logging output of a script. 1 is the file descriptor for STDOUT and 2 is the file descriptor for STDERR so you can modify each as appropriate - for example send logging to one file and errors to another file.




