Bash Scripting – Redirecting output in scripts
You can use the STDOUT and STDERR file descriptors in your scripts to produce output in multiple locations simply by redirecting the appropriate file descriptors. There are two methods for redirecting output in the script:
- Temporarily redirecting each line
- Permanently redirecting all commands in the script
If you want to purposely generate error messages in your script, you can redirect an individual output line to STDERR. You just need to use the output redirection symbol to redirect the output to the STDERR file descriptor. When you redirect to a file descriptor, you must precede the file descriptor number with an ampersand (&):
echo “This is an error message” >&2
$ cat test8 #!/bin/bash # testing STDERR messages echo “This is an error” >&2 echo “This is normal output” $
$ ./test8 This is an error This is normal output $
If you have lots of data that you’re redirecting in your script, it can get tedious having to redirect every echo statement. Instead, you can tell the shell to redirect a specific file descriptor for the duration of the script by using the exec command:
$ cat test10 #!/bin/bash # redirecting all output to a file exec 1>testout echo “This is a test of redirecting all output” echo “from a script to another file.” echo “without having to redirect every individual line” $ ./test10 $ cat testout This is a test of redirecting all output from a script to another file. without having to redirect every individual line $
You can also redirect the STDOUT in the middle of a script:
$ cat test11 #!/bin/bash # redirecting output to different locations exec 2>testerror echo “This is the start of the script” echo “now redirecting all output to another location” exec 1>testout echo “This output should go to the testout file” echo “but this should go to the testerror file” >&2 $ $ ./test11 This is the start of the script now redirecting all output to another location $ cat testout This output should go to the testout file $ cat testerror but this should go to the testerror file $
The script uses the exec command to redirect any output going to STDERR to the file testerror. Next, the script uses the echo statement to display a few lines to STDOUT. After that, the exec command is used again to redirect STDOUT to the testout file. Notice that even whenSTDOUT is redirected, you can still specify the output from an echo statement to go to STDERR, which in this case is still redirected to thetesterror file.
After you redirect STDOUT or STDERR, you can’t easily redirect them back to their original location. If you need to switch back and forth with your redirection, you need to learn a trick. The “Creating Your Own Redirection” section later in this chapter discusses this trick and how to use it in your shell scripts.