Difference between revisions of "BASH Flow Control"

From CDOT Wiki
Jump to: navigation, search
(New page: BASH provides a number of flow control constructs. = if = Format: if ''pipeline'' then ''success-commands'' <nowiki>[</nowiki>elif ''pipeline2'' ''else-if-commands'' <nowi...)
 
Line 126: Line 126:
 
   *)    echo "did you mean yes or no?!" ;;
 
   *)    echo "did you mean yes or no?!" ;;
 
  esac
 
  esac
 +
 +
[[Category:BASH]][[Category:Linux]]

Revision as of 07:37, 16 September 2008

BASH provides a number of flow control constructs.

if

Format:

if pipeline
then
  success-commands
[elif pipeline2
  else-if-commands
]
[else
  alt-commands
]
fi

Executes success-commands if pipeline returns an exit code of zero.

If success-commands returns a non-zero exit code and pipeline2 returns an exit code of zero, executes else-if-commands.

Otherwise, executes alt-commands.

Examples:

if grep -q "jason" /etc/passwd
then
  echo "the user 'jason' exists in the passwd file."
else
  echo "the user 'jason' does not exist in the passwd file."
fi
echo -n "Are you sure you wish to remove '$file'?"
ready YN
if [ "$YN" = "y" -o "$YN" = "Y" ]
then
   echo "Deleting '$file'..."
   rm "$file"
else
   echo "Aborted. '$file' not deleted."
fi
if [ "$(date +%Y)" -lt 2010 ]
then
   echo "Still waiting for the Whistler Olympics."
fi

while

Format:

while pipeline
do
  commands
done

Executes commands once for each time that pipeline returns a true result (exit code of zero). Example:

!!!!!!!!! Need example !!!!!!!!!!

for (list)

for variable in list
do
   commands
done

Examples:

for COLOUR in red blue green
do
   print "$COLOUR"
done
for FILE in /etc/*
do
   if [ -x $FILE ]
   then
      echo "$FILE is executable"
   fi
done
for MOUNT in $(mount|sed "/\//s/^.*on \([^ ]*\) .*$/\1/")
do
  du -sx $MOUNT
done


for (numeric)

This is a C-style for loop:

for (( variable=start ; condition ; interation-action ))
do
   commands
done

The value of variable is initially set to the integer value start, and commands are executed repeatedly, performing iteraction-action each time until condition is no longer true. Note that this loop is performed in the BASH Math context, and therefore condition is written with symbols such as <, >, <=, and >= instead of -lt, -gt, -le, and ge.

Example:

for ((x=0; x<=10; x++))
do 
   echo $x
done

case

case expression in
pattern1[|pattern1b...])
  commands1
  ;;
[pattern2[|pattern2b...])
  commands2
  ;; ...]
esac

Executes the first group of commands for which the corresponding pattern(s) match the expression. The matching is done using globbing rules.

Example:

read x
case "$x" in
  y*|Y*) echo "Interpreting that as 'yes'" ;;
  n*|N*) echo "Interpreting that as 'no'" ;;
  *)     echo "did you mean yes or no?!" ;;
esac