Shell Script Examples
(March 2004)

The following examples may be used with sh, ksh and bash
(not with csh, tcsh).

Command Line Arguments

while [ "$1" != "" ]; do
	case $1 in
		-i) interactive=1; shift;;
		-b) background=1; shift;;
		*) echo "$0 [-b|-i]"; exit 1;;
	esac
done

Interactive Prompt

ask() {
	answer=""
	while [ -z $answer ]; do
		echo "$1 (y/n)"
		read answer
		if [ "$answer" = "y" ]; then return 0
		elif [ "$answer" = "n" ]; then return 1
		else answer=""
		fi
	done
}
ask "Continue ?" || exit

Incrementing a value

i=`expr $i + 1`

Recursive calls

myfunction() {
        local arg=$1
	if [ $arg -gt 0 ]; then
		myfunction `expr $arg - 1`
	fi
	echo "$arg done."
}
myfunction 4