🔄

Bash Scripting with Loops Overview

Nov 26, 2024

Bash Scripting: Loops

Introduction

  • Bash scripting allows for automation and execution of complex workflows.
  • Key feature of bash scripting: loops.
  • Four types of loops in bash:
    • for VARIABLE in LIST
    • for (( ; ; ))
    • while EXPR
    • until EXPR

for VARIABLE in LIST

  • Iterates through a list of values, executing the loop body for each value.
  • Example: for X in 1 2 3 do ... body of the loop ... done for COLOUR in red green blue do ... body of the loop ... done
  • Can use script parameters as list values with $@.
  • Can match filenames using globbing patterns, e.g., *.c.
  • If no match is found, the pattern is assigned to the variable.

Example: Compile C Source Files

for SOURCEFILE in *.c do echo "=== Compiling $SOURCEFILE ===" BINARY="$(echo $SOURCEFILE | cut -d. -f1)" gcc SOURCEFILE -o $BINARY done

C-style for Loop: for (( ; ; ))

  • Similar to C language for loops.
  • Uses bash arithmetic syntax (( )) and do/done for body.
  • Contains initial condition, control condition, and increment/decrement.

Example: Count from 1 to 10

for (( i=0; i<=10; i++ )) do echo $i done

while EXPR

  • Continues as long as the expression is true.
  • Expression can be a single command, list of commands, or pipeline.
  • Commonly uses the test command [[ ]].

Example

while [[ "$A" == "$B" ]] do ... body of the loop ... done

until EXPR

  • Continues as long as the expression is false.
  • Stops when expression becomes true.

Example

until [[ "$X" -gt "$Y" ]] do ... body of the loop ... done

Examples from Lecture

tput Colour Codes

  • tput command uses terminal codes for actions like setting text color.
  • tput setaf _n_ and tput setab _n_ set foreground and background colors.
#!/usr/bin/bash for ((C=0; C<16; C++)) do tput setaf $C echo "This is colour $C" done tput sgr0

Number-Guessing Game

  • Interactive script where the player guesses a secret number.
#!/usr/bin/bash MAX=100 MAX_TRIES=7 GAMES=0 WINS=0 clear tput setaf 5 while [[ "$PLAY" == "Y" || "$PLAY" == "y" || "$PLAY" == "YES" || "$PLAY" == "Yes" || "$PLAY" == "yes" ]] do SECRET=$(( RANDOM % MAX + 1 )) GUESS=0 TRIES=0 ((GAMES++)) until [[ $GUESS -eq $SECRET || $TRIES -ge $MAX_TRIES ]] do tput setaf 15 read -p "Enter your guess (#$((++TRIES))): " GUESS if [[ $GUESS -gt $SECRET ]] then tput setaf 1 echo "Too high!" elif [[ $GUESS -lt $SECRET ]] then tput setaf 1 echo "Too low!" else tput setaf 10 echo "You got it in $((TRIES)) tries!" ((WINS++)) fi echo done if [[ ! $GUESS -eq $SECRET ]] then tput setaf 11 echo "You lose after $TRIES attempts. The number was $SECRET." fi tput setaf 15 read -p "Do you want to play again (Y/N)? " PLAY echo done tput setaf 5 echo "You executed $GAMES missions and succeeded $WINS times ($((WINS*100/GAMES))% success)." echo tput sgr0