Bash Shell Programming

Bash is my preferred console shell and scripting language. I use it mainly to script the execution of running various experiments or applications. I use too many different programming langauges to remember the syntax for any of them, so here are some of the basic control mechanisms that come up often.

The Very Basics

  • Assign to a variable with: var1=34
  • Variables are preceeded by a $ when being accessed: echo $var1
  • Spacing is important: var1 = 34 ## produces an error
  • More thorough introductions: here and here
  • Reference cards here

Preset Variables

Some useful variables are:

  • $1, $2, $3, etc = the command line arguments passed to the script.
  • $0 = the name of the script
  • $# = number of argument passed
  • $! = process id of last executed process

Control Flow

Examples are below.

#If/else statements
if [ -z $1 ]
then
    echo "No argument provided!"
    exit
else
    echo "arg 1 = $1"
fi

#For loop from 5...10
for i in $(seq 5 10)
do
    echo $i
done

# case/switch:
case "$type" in
    "init" )
        echo "case init"
        ;;
    "end" )
        echo "case end"
        ;;
    * )
        echo "default case"
esac

#functions
function myecho {
    # arguments to function are like arguments to a script
    echo $1
}
myecho "hello world"

Arithmetic

You can do integer math easily with code like:

z=$(($z+3))
a=$((5+10/2))

Floating point can be done with the help of external programs like bc:

#C like syntax, scale tells how many decimal places to use
a=`echo "scale=4; 1/4" | bc`        # a = "0.2500"
b=`echo "scale=4; $a*2" | bc`       # b = "0.5000"

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>