CodeTheRobot

Ubuntu Linux for Robotics · Lesson 19 of 96

Shell scripting: loops and conditions

if, test, for, while, case, functions and reading command output.

Estimated time · 60–90 min

Learning goals

What you will understand

  • Explain shell scripting: loops and conditions in your own words
  • Use it in a small workstation example
  • Verify the result instead of assuming it worked

Understand the idea first

The mental model

if [ condition ]; then ... fi runs code when a test is true. Tests include -f file (exists), -d folder, -z string (empty), and comparisons: -eq -lt -gt for numbers and = for strings. for x in list and while condition repeat commands; case chooses among patterns; functions group commands (name() { ...; }).

Capture a command's output with $(command). Always quote variables in tests, and use [[ ]] in bash for safer string tests. A useful robotics script checks that a device exists, waits for it in a loop with a timeout, and prints a clear error if it never appears.

Guided lesson

Work through these steps

  1. 1.

    Open a terminal and record the current state before changing anything.

  2. 2.

    Read the shell scripting: loops and conditions commands and predict what each one does.

  3. 3.

    Run the commands one at a time and compare each output with your prediction.

  4. 4.

    Write the commands that worked in a setup note you can repeat later.

Worked example

Read it before you run it

for i in 1 2 3; do echo "cycle $i"; done
# Repeat a command for each value.
if [ -e /dev/ttyUSB0 ]; then echo found; else echo missing; fi
# Check for a device before using it.
count=0; while [ "$count" -lt 5 ]; do count=$((count + 1)); done
# Count up to five with arithmetic.
case "$1" in start) echo starting;; stop) echo stopping;; *) echo usage;; esac
# Choose an action from the first argument.
wait_for() { for i in $(seq 1 10); do [ -e "$1" ] && return 0; sleep 1; done; return 1; }
# A function that waits up to ten seconds for a file.
files=$(ls /etc | wc -l); echo "$files entries"
# Capture command output into a variable.

What the example is doing

  1. 1.Lines without sudo only inspect or change files you own; sudo authorizes a system-wide change.
  2. 2.Read command output before moving to the next line. Stop if names, versions, disks, or paths differ from the lesson.
  3. 3.Comments beginning with # explain safety checks and are not executed by the shell.

Watch it run · Build and run

See what this code does

The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.

sourcecompilerprogramBUILD AND RUN

Demo for Shell scripting: loops and conditions. Expected result: sum=15 even=2

Practice code

Now type it yourself

Open a terminal, run the starter line by line (or save it as practice.sh and run bash practice.sh), and replace every TODO with your own command.

sum=0
even=0
for i in 1 2 3 4 5; do
  # TODO: add i to sum; when i is even (i % 2 == 0) also add 1 to even
done
echo "sum=$sum"
echo "even=$even"

Expected output

sum=15
even=2
Stuck? Show the full solution (try it yourself first)
sum=0
even=0
for i in 1 2 3 4 5; do
  sum=$((sum + i))
  if [ $((i % 2)) -eq 0 ]; then even=$((even + 1)); fi
done
echo "sum=$sum"
echo "even=$even"

Expected result

How you know it worked

  • Each command completes without an unexplained error.
  • Your notes contain the command, the important output, and what it proves.

Practical exercise

Apply the lesson

Write check_robot.sh that verifies a serial device exists (waiting up to 10 seconds), that ROS is installed (/opt/ros), and that free disk space is above 5 GB, printing OK or FAIL for each and exiting non-zero if any fail.

Before you continue

  • You recorded the starting state
  • Every command and output is understood
  • The change can be repeated from your notes

If something goes wrong

A command says permission denied.

Check ownership and permissions first. Do not add sudo unless the command changes a documented system location.

A command or package is not found.

Check spelling, Ubuntu version, enabled repositories, and whether the previous installation command succeeded.