Wednesday, October 22, 2008

Bash Script Tips

http://www.hsrl.rutgers.edu/ug/shell_help.html

Command line arguments to shell scripts are positional variables:
$0, $1, ... - The command and arguments.
   With $0 the command and the rest the arguments.

$# - The number of arguments.
$*, $@ - All the arguments as a blank separated string.
  Watch out for "$*" vs. "$@".
  And, some commands: shift

$$ - Current process id.
$? - The exit status of the last command. and return result of last function

Conditional Reference
${variable-word} - If the variable has been set, use it's value, else use word.

POSTSCRIPT=first;
echo POSTSCRIPT
POSTSCRIPT=${POSTSCRIPT-second};
export POSTSCRIPT
echo POSTSCRIPT

${variable:-word} - If the variable has been set and is not null, use it's value, else use word.

These are useful constructions for honoring the user environment.
Ie. the user of the script can override variable assignments. Cf. programs like lpr(1) honor the PRINTER environment variable, you can do the same trick with your shell scripts.

${variable:?word} -If variable is set use it's value, else print out word and exit. Useful for bailing out.

String concatenation
The braces are required for concatenation constructs.
$p_01 - The value of the variable "p_01".
${p}_01 - The value of the variable "p" with "_01" pasted onto the end.

Include configuration
. command

This runs the shell script from within the current shell script. For example:
# Read in configuration information
. /etc/hostconfig

Debugging
The shell has a number of flags that make debugging easier:
sh -n command -

Read the shell script but don't execute the commands. IE. check syntax.
sh -x command
Display commands and arguments as they're executed. In a lot of my shell scripts you'll see
# Uncomment the next line for testing
# set -x

No comments: