0
0
Bash Scriptingscripting~5 mins

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

Choose your learning style9 modes available
Recall & Review
beginner
What is the basic syntax of an if-then-else statement in Bash?
The basic syntax is:<br>
if [ condition ]; then<br>  commands<br>else<br>  other_commands<br>fi
<br>This checks the condition; if true, runs commands, else runs other_commands.
Click to reveal answer
beginner
How do you check if a file exists using if-then-else in Bash?
Use the test command with -e:<br>
if [ -e filename ]; then<br>  echo "File exists"<br>else<br>  echo "File does not exist"<br>fi
Click to reveal answer
beginner
What does the 'fi' keyword do in a Bash if-then-else statement?
'fi' marks the end of the if statement. It is 'if' spelled backward and tells Bash where the if block finishes.
Click to reveal answer
beginner
Can you use multiple commands inside the then or else blocks? How?
Yes, you can put many commands inside then or else blocks by writing them on separate lines:<br>
if [ condition ]; then<br>  command1<br>  command2<br>else<br>  command3<br>  command4<br>fi
Click to reveal answer
beginner
What happens if the condition in an if statement is false and there is no else block?
If the condition is false and no else block exists, Bash simply skips the then block and continues running the script after fi.
Click to reveal answer
Which keyword ends an if-then-else block in Bash?
Adone
Bend
Cfi
Dstop
What symbol is used to test a condition in an if statement?
A{}
B[]
C()
D<>
How do you write an else block in Bash?
Aelse { commands }
Belse: commands
Celse commands
Delse followed by commands on next lines
What will this script print if the file 'test.txt' does not exist?<br>if [ -e test.txt ]; then echo "Found"; else echo "Not found"; fi
ANot found
BNothing
CError
DFound
Can you put multiple commands inside the then block?
AYes, separated by semicolons or new lines
BNo, only one command is allowed
COnly if you use curly braces
DOnly if you use parentheses
Explain how an if-then-else statement works in Bash with an example.
Think about checking a condition and running different commands based on true or false.
You got /6 concepts.
    Describe how to check if a file exists using if-then-else in Bash and what happens if the file does not exist.
    Use the test command inside the if condition.
    You got /5 concepts.