These classnotes are depreciated. As of 2005, I no longer teach the classes. Notes will remain online for legacy purposes

UNIX01/Conditionals

Classnotes | UNIX01 | RecentChanges | Preferences

if condition

The if condition places a condition on commands. That condition is the exit status of a specific Linux command. If the command is successful, then the commands within the if structure are executed. If the command was not successful, then the command has failed and the commands in the if structure are not executed. The basic syntax for if is

 if Linux command
   then
      commands
   else
      commands
 fi

The if command begins with the keyword if and is followed by a Linux command whose exit status will be evaluated. This first command is always executed. After the command, the keyword then goes on a line by itself. Any set of commands may then follow. The keyword fi ends the if structure. If the Linux command fails, and an else command is present, then the commands after else are executed.

case

The case structure chooses among several possible alternatives. The choice is made by comparing a value with several possible patterns. Each possible pattern is associated with a set of operations. If a match is found, the associated operations are performed. The basic syntax is as follows

 case variable in
   pattern)
      commands
      ;;
   pattern)
      commands
      ;;
   *)
      default commands
      ;;
 esac

The case structure begins withe the keyword "case". A set of patterns then follows. Each patter is a regular expression terminated with a closing parenthesis. After the closing paranthesis, commands associated with the pattern are listed, followed by a double semicolon on a separate line designating the end of those commands. After all of the listed patterns, the keyword esac ends the case command.

As a simple example, let's say we wanted to check the variable $choice to see whether it contained "a", "b", "c", or anything else, we would use

 case $choice in
   a)
      echo It was a
      ;;
   b)
      echo It was b
      ;;
   c)
      echo It was c
      ;;
   *)
      echo It was not a or b or c
      ;;
 esac


Classnotes | UNIX01 | RecentChanges | Preferences
This page is read-only | View other revisions
Last edited July 26, 2003 4:07 am (diff)
Search:
(C) Copyright 2003 Samuel Hart
Creative Commons License
This work is licensed under a Creative Commons License.