Mission 26 of 30
Shell Scripting Control Structures
Make a script respond clearly to arguments, conditions, and failures.
Use if/else, for loops, while loops, and case statements in practice scripts.
Practice inside
~/linux-practice. Check your setup before you begin.
Prerequisite: Shell Scripting Basics
.
What you’ll practice
- Write conditionals
- Loop over values/files
- Use case statements
The mental model
- Quote variables in tests when possible.
- Spaces around [ and ] matter.
- Loops repeat commands predictably.
Try it in your terminal
If/else demo
Safe in practice folderCreates a basic conditional script.
Run from ~/linux-practice
cd ~/linux-practice/scripts
cat << 'EOF' > if_demo.sh
#!/usr/bin/env bash
num=${1:-10}
if [ "$num" -gt 10 ]; then
echo "Greater than 10"
elif [ "$num" -eq 10 ]; then
echo "Exactly 10"
else
echo "Less than 10"
fi
EOF
chmod +x if_demo.sh
./if_demo.sh 25 For loop
Safe in practice folderLoops over fixed words. Saved in scripts/ alongside if_demo.sh.
Run from ~/linux-practice
cd ~/linux-practice/scripts
cat << 'EOF' > for_demo.sh
#!/usr/bin/env bash
for fruit in apple banana cherry; do
echo "I like $fruit"
done
EOF
chmod +x for_demo.sh
./for_demo.sh Case statement
Safe in practice folderMatches one value against multiple patterns. Saved in scripts/ alongside the other demo scripts.
Run from ~/linux-practice
cd ~/linux-practice/scripts
cat << 'EOF' > case_demo.sh
#!/usr/bin/env bash
answer=${1:-yes}
case "$answer" in
yes|y|YES|Y) echo "You agreed." ;;
no|n|NO|N) echo "You disagreed." ;;
*) echo "Invalid input" ;;
esac
EOF
chmod +x case_demo.sh
./case_demo.sh yes Put it into practice
- Write a script that accepts a filename and says whether it exists.
Check your result
Valid and invalid inputs take the expected branches.
Common mistakes
- You type `if [$num -gt 10]` and get 'command not found.' Bash needs spaces inside the brackets: `if [ $num -gt 10 ]`. The brackets are actually a command, and spaces are how it parses its arguments.
- You store a filename with spaces in a variable, use it unquoted, and watch your script explode. `myfile=$'my file.txt'` then `rm $myfile` becomes `rm my file.txt` — two files, not one. Always quote: `rm "$myfile"`.
Check your understanding
Explain these in your own words. If you’re unsure, revisit the examples before moving on.
- Which statement handles many possible text values?
- Why should variables often be quoted?
Your practice, your pace
Loading saved progress…