image001


Shell Programming 2: Some more examples and features


 C-like Loops

The shell has C-like for loops: example C-loops.sh

 

The useful expr command

Note the expr command gives the shell simple math capabilities: example while.sh:

 

#!/bin/sh

#

#Script to test while statement

 

if [ $# -eq 0 ]

then

   echo "Error - Number missing form command line argument"

   echo "Syntax : $0 number"

   echo " Use to print multiplication table for given number"

   exit 1

fi

 

n=$1

i=1

while [ $i -le 10 ]

do

  echo "$n * $i = `expr $i \* $n`"

  i=`expr $i + 1`

done

 

Shell functions

the shell has functions: also example file.sh

Substring replacement

The shell lets you pick out a substring from a variable: see substr1.sh

 

You can also do sed-like replacements: see substr2.sh

 

Here documents

Here documents let you embed the stdin to a program you call in a code block in your script. Example.