Automatically Saving Script Output Using the tee UtilityIstván Bátori, August 2007 IntroductionThis tip helps you to save script output by using the tee utility. You can use the script I provide below under "Installation." This tip corresponds to the tip Automatically Saving Script Output Using the nohup Utility. I have created tons of scripts for administrators, and I was interested in how script output can be saved in an easy, elegant way. Scripts can have their own logging functions, but the output also contains important information. Saving the output is typically solved by output redirection, for example: myscript.sh 2>&1 | tee /var/log/myscript.log How do you feel about typing such a long command? Isn't it boring? It's a lot to type. And it's confusing to read the long, uninteresting ballast in an admin document, especially if the script has many arguments and options and the log file contains the start date. The #!/usr/bin/ksh /opt/bin/tee.sh That's all! The script is started automatically by This method is usable for shell, Perl, Python, or Ruby scripts, and it is easy to extend for other script languages. First, let me explain the trick I use. Script File ExecutionUNIX executes a script file according to its first line: #! <exec_command> [<args...>] The system invokes the first line and passes the script file name
and the command-line arguments. For example, the #!/usr/bin/ksh If you type this at the command prompt: foo.sh /tmp 3 1 The following is invoked: /usr/bin/ksh foo.sh /tmp 3 1 If #!/usr/bin/ksh /opt/bin/tee.sh The following is invoked: /usr/bin/ksh /opt/bin/tee.sh foo.sh /tmp 3 1
tee.sh Installation and UsageInstallation
Copy the tee.txt
file, changing the ".txt" suffix to ".sh", and save into the cp tee.sh /opt/bin chmod 755 /opt/bin/tee.sh chown root:admin /opt/bin/tee.sh Usage There are two different ways to use the wrapper script: 1. Start the wrapper script directly from the command line: /opt/bin/tee.sh <command> [<args...>] For example: /opt/bin/tee.sh foo.sh 2. Put the following into a script as the first line: #!/usr/bin/ksh /opt/bin/tee.sh For example: cat >/tmp/tee_test.sh <<EOF #!/usr/bin/ksh /opt/bin/tee.sh # example script to demonstrate tee.sh usage echo "hello world" EOF
Executing ConfigurationBoth usage methods have the same functionality. The functionality can be configured by shell variables, as follows:
Note: There is a bug (but it's not really a big one): Unless otherwise licensed, code in all technical manuals herein (including articles, FAQs, samples) is provided under this License. |
BigAdmin SubscriptionsBigAdmin Areas
BigAdmin Sun Center
BigAdmin Topics | |||