UNIX Scripting
A summary of useful tips and tricks as can be found on different (web)-pages such as:
- Russel Quong [1], A guide for writing scripts.
- Mendel Cooper [2], Advanced Bash Scripting Guide. An in-depth exploration of the art of shell scripting.
Debugging Scripts
- Use echo statements.
- Run bash -n script to check for syntax errors.
- Use the command set -v to get a verbose dump of each line the shell reads.
Use set +v to turn off verbose mode. - Use the command set -x to see what each command expands to.
Again, set +x turns this mode off.
Command line arguments
The command line parameters to a script are stored in the nearly identical variables $* and $.
The following table summarizes the variables you would use for command line processing.
For the example values, assume you wrote a bash script /usr/bin/args.sh and ran it as shown below.
Variable | Meaning | Example: echoArgs -t two "let's go" |
---|---|---|
$* | Command line args | -t two let's go |
$@ | Command line args | -t two "let's go" |
$# | Number of args | 3 |
$0 | Name of script | /usr/bin/args.sh |
$1 | First arg in $* | -t |
$2 | Second arg in $* | two |
$3 | Third arg in $* | let's go |
$4 | Fourth arg in $* | (empty) |
echoArgs () { echo $# for i in "$@"; do echo "($i)"; done; for i in $*; do echo "(($i))"; done } $ echoArgs -t two "let's go" 3 (-t) (two) (let's go) ((-t)) ((two)) ((let's)) ((go))
Command Line Options
I prefer the usage of case statements in stead of the getops.
Flag | Description |
---|---|
-o OUT | Sends output to file OUT |
-n | Shows what you would do but do not do it |
-v | Gives more output, each -v increases verboseness |
-l | Same as -verbose |
-version | Shows the version and quit |
nflag=0 vlevel=0 OUT= while [ $# -gt 0 ] do case "$1" in -o ) OUT=$2 ; shift 2 ;; -n ) nflag=1 ; shift ;; -l | -v ) vlevel=$(( vlevel+1 )) ; shift ;; -ver* ) echo "Version $version" ; exit 1 ;; * ) echo "Saw non flag $arg" ; break ;; esac done
See also
- Shell-Differences Short overview of different shells
- Overview, Short overview of different shells
- Csh Whynot, List of csh problems
Reference
- ↑ Russel Quong, A guide to writing shell scripts for C/C++/Java and unix programmers.
- ↑ Mendel Cooper Advanced Bash-Scripting Guide. Very extensive Guide with a lot of examples.