0
0
Bash Scriptingscripting~5 mins

if-elif-else in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the if statement in bash scripting?
The if statement lets the script make decisions by running commands only if a condition is true.
Click to reveal answer
beginner
How do you write an elif branch in bash scripting?
Use elif [ condition ]; then to check another condition if the first if was false.
Click to reveal answer
beginner
What does the else block do in an if-elif-else structure?
The else block runs commands when all previous if and elif conditions are false.
Click to reveal answer
intermediate
Write a simple bash if-elif-else structure to check if a number is positive, negative, or zero.
Example:
if [ "$num" -gt 0 ]; then
  echo "Positive"
elif [ "$num" -lt 0 ]; then
  echo "Negative"
else
  echo "Zero"
fi
Click to reveal answer
beginner
Why do you need to use fi in bash scripts?
Because fi marks the end of an if block, telling the shell where the conditional ends.
Click to reveal answer
In bash scripting, which keyword starts an alternative condition after if?
Aelif
Belse
Cendif
Delseif
What symbol ends an if block in bash?
Aend
Bdone
Cfi
Dstop
What happens if all if and elif conditions are false and there is no else block?
AThe script restarts
BThe script runs the last <code>elif</code> block
CThe script throws an error
DNo commands inside the <code>if</code> structure run
Which of these is the correct syntax for an if condition in bash?
Aif (condition) { }
Bif [ condition ]; then
Cif condition then
Dif { condition }
What does the else block do in an if-elif-else statement?
ARuns if all previous conditions are false
BEnds the script
CRuns only if <code>elif</code> is true
DRuns if the first <code>if</code> is true
Explain how an if-elif-else structure works in bash scripting.
Think about how you decide between multiple choices in real life.
You got /4 concepts.
    Write a bash script snippet using if-elif-else to check if a variable is equal to 'yes', 'no', or something else.
    Use square brackets and remember to close with fi.
    You got /4 concepts.