Suggested day 2620–30 minutesSafe in practice folder

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.

Outcome: Scripts can make decisions, not just run a fixed list of commands.

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

1

If/else demo

Safe

Creates a basic conditional script.

Terminal
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
2

For loop

Safe

Loops over fixed words. Saved in scripts/ alongside if_demo.sh.

Terminal
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
3

Case statement

Safe

Matches one value against multiple patterns. Saved in scripts/ alongside the other demo scripts.

Terminal
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

Checkpoint

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?

Shortcuts:Alt + ← previous lessonAlt + → next lessonAlt + H home? focus search