Jump to content

Control structures: Difference between revisions

From Squishu Wiki
No edit summary
No edit summary
 
(4 intermediate revisions by the same user not shown)
Line 23: Line 23:
...
...
fi
fi
<pre>


You an put then on the same line, but then you have to use a semi
You an put then on the same line, but then you have to use a semi
Line 41: Line 44:
   echo "good afternoon"
   echo "good afternoon"
fi
fi
</pre>
* elif
* example:  elif that exits with error code when given bad input
<pre>
echo "Is it morning?  Please answer yes or no"
read timeofday
if [ $timeofday = "yes" ]; then
  echo "good morning"
elif [ $timeofday = "no" ]; then
  echo "good afternoon"
else
  echo "Sorry, $timeoday not recognized.  Enter yes or no"
  exit 1
fi
</pre>
* See book p36, there is some weird reason you should always double quote variables in contional checks
** Ex:  use "$timeofday" instead of $timeofday
** Really don't understand this
* If the variable can never be the empty string, you don't need to protect it with double quotes when testing its value.  Still, always double quote variables because it's a good habit

Latest revision as of 19:18, 5 July 2025

General

Simple if statement

  • The general structure of an if statement
if condition
then
  statements
else
  statements
fi
if test -f blah.py
then
...
fi

if [ -f blah.py ]
then
...
fi

<pre>


You an put then on the same line, but then you have to use a semi

if [ -f blah.py ]; then
...
fi
  • if statement after reading user input
echo "Is it morning?  Please answer yes or no"
read timeofday

if [ $timeofday = "yes" ]; then
  echo "good morning"
else
  echo "good afternoon"
fi
  • elif
  • example: elif that exits with error code when given bad input
echo "Is it morning?  Please answer yes or no"
read timeofday

if [ $timeofday = "yes" ]; then
  echo "good morning"
elif [ $timeofday = "no" ]; then
  echo "good afternoon"
else
  echo "Sorry, $timeoday not recognized.  Enter yes or no"
  exit 1
fi
  • See book p36, there is some weird reason you should always double quote variables in contional checks
    • Ex: use "$timeofday" instead of $timeofday
    • Really don't understand this
  • If the variable can never be the empty string, you don't need to protect it with double quotes when testing its value. Still, always double quote variables because it's a good habit