Automatically Saving Program Output With a nohup ScriptIstván Bátori, August 2007 IntroductionThis tip can help you save script output by using the 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: nohup mynohupscript.sh >/var/log/myscript.log 2>&1 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/nohup.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/nohup.sh The following is invoked: /usr/bin/ksh /opt/bin/nohup.sh foo.sh /tmp 3 1
nohup.sh Installation and UsageInstallation Copy the nohup.txt
file, changing the ".txt" suffix to ".sh", and save into the cp nohup.sh /opt/bin chmod 755 /opt/bin/nohup.sh chown root:admin /opt/bin/nohup.sh Usage There are two different ways to use the wrapper script: 1. Start the wrapper script directly from the command line: /opt/bin/nohup.sh <command> [<args...>] For example: /opt/bin/nohup.sh foo.sh 2. Put the following into a script as the first line: #!/usr/bin/ksh /opt/bin/nohup.sh For example:
cat >/tmp/nohup_test.sh <<EOF
#!/usr/bin/ksh /opt/bin/nohup.sh
# example script to demonstrate nohup.sh usage
default_cycles=3
default_sleeping=1
cycles=${1:-$default_cycles}
sleeping=${2:-$default_sleeping}
i=0
while [[ $i -lt $cycles ]]
do
echo "$(date): $i"
sleep $sleeping
i=$((i+1))
done
EOF
Executing ConfigurationBoth usage methods have the same functionality. The functionality can be configured by shell variables, as follows:
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 | |||