Bash - While, Until, and For Loops

Question Click to View Answer

Use a while loop to print the numbers 1, 2, 3, 4, and 5 to the Terminal.

counter=1
while [ $counter -lt 6 ]; do
  echo $counter
  counter=$(( $counter + 1 ))
done

Use an until loop to print the number 1, 2, 3, 4, and 5 to the Terminal.

i=1
until [ $i -gt 5 ]; do
  echo $i
  i=$(( $i + 1 ))
done

Use while to create an infinite loop that prints 1, 2, and 3 to the Terminal.

j=1
while true; do
  if [[ $j -eq 4 ]]; then
    break
  fi
  echo $j
  j=$(( $j + 1 ))
done

The break command causes the loop to exit.

Use while to create a loop that prints 1, 2, 4, and 5 to the Terminal (notice that 3 is skipped).

k=1
while [ $k -lt 6 ]; do
  if [ $k -eq 3 ]; then
    k=$(( $k + 1 ))
    continue
  fi
  echo $k
  k=$(( $k + 1 ))
done

The continue command causes the rest of the current loop to be skipped, but does not exit the loop completely like the break command.

Create a loop that endlessly prints "This never ends...". Then exit from the loop.

while true; do
  echo "This never ends..."
done

Press Control + c to exit the infinite loop.

Use a for loop to iterate over the list snake, rat, cat and print the words to the Terminal.

for animal in sake rat cat; do
  echo $animal
done

Use a for loop to sum the numbers from 1 to 20 (i.e. 1 + 2 + 3 + .. + 20).

result=0
for i in {1..20}; do
  result=$(( $result + $i ))
done
echo $result

Explain what the following code prints:

blah=
if [ -z $blah ]; then
  echo "blah blah blah"
else
  echo "no no no"
fi
blah blah blah

[ -z $blah ] returns an exit status of 0 if the variable is not assigned to a value. The blah variable is not assigned a value in this example.

Print the number of characters in the string assigned to the flag variable.

flag="stars-n-stripes"
echo ${#flag}

Use a for loop to find the longest word in the following list: lions, tigers, bears, flying_monkeys.

longest_word=
for i in lions tigers bears flying_monkeys; do
  if [ -z $longest_word ] || [ ${#i} -gt ${#longest_word} ]; then
    longest_word=$i
  fi
done
echo $longest_word

Use the C-style for loop syntax to print the numbers 1, 2, 3, ..., 10.

for (( i=1; i<11; i=i+1 )); do
  echo $i
done