Mission 1 of 5
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.
Mental model
Understand what is happening
Quote variables in tests when possible.
Spaces around [ and ] matter.
Loops repeat commands predictably.
Guided lab
Work through the mission
If/else demo
Creates a basic conditional script.
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 25For loop
Loops over fixed words. Saved in scripts/ alongside if_demo.sh.
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.shCase statement
Matches one value against multiple patterns. Saved in scripts/ alongside the other demo scripts.
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 yesCheckpoint
Verify the mission
Valid and invalid inputs take the expected branches.
Try it yourself
One step without a recipe
Write a script that accepts a filename and says whether it exists.
Need a hint?
When your `[` test breaks, add `echo` before the condition. Print the values you're comparing. Nine times out of ten, a variable is empty or has a space you didn't expect. See the values, fix the bug.
Explain it back
Before you move on
- Which statement handles many possible text values?
- Why should variables often be quoted?