Conditionals

The if statement chooses between alternatives, each of which may have a complex test. The simplest form is the if-then statement:

if command           If exit status of command is 0
then
  body
fi

For example:

if [ `whoami` = "root" ]
then
  echo "You are the superuser"
fi

Next is the if-then-else statement:

if command
then
  body1
else
  body2
fi

For example:

if [ `whoami` = "root" ]
then
  echo "You are the superuser"
else
  echo "You are an ordinary dude"
fi

Finally, we have the form if-then-elif-else, which may have as many tests as you like:

if command1
then
  body1
elif command2
then
  body2
elif ...
  ...
else
  bodyN
fi

For example:

if [ `whoami` = "root" ]
then
  echo "You are the superuser"
elif [ "$USER" = "root" ]
then
  echo "You might be the superuser"
elif [ "$bribe" -gt 10000 ]
then
  echo "You can pay to be the superuser"
else
  echo "You are still an ordinary dude"
fi

The case statement evaluates a single value and branches to an appropriate piece of code:

echo "What would you like to do?"
read answer
case "$answer" in
  eat)
    echo "OK, have a hamburger"
    ;;
  sleep)
    echo "Good night then"
    ;;
  *)
    echo "I'm not sure what you want to do"
    echo "I guess I'll see you tomorrow"
    ;;
esac

The general form is:

case string in
  expr1)
    body1
    ;;
  expr2)
    body2
    ;;
  ...
  exprN)
    bodyN
    ;;
  *)
    bodyelse
    ;;
esac

where string is any value, usually a variable value like $myvar, and expr1 through exprN are patterns (run the command info bash reserved case for details), with the final * like a final “else.” Each set of commands must be terminated ...

Get Linux Pocket Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.