Help with loops?

I'm trying to understand better the while and until loops, can someone help me with this example?

#!/bin/bash
# Listing the planets.

for planet in Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto
do
  echo $planet  # Each planet on a separate line.
done

echo; echo

for planet in "Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto"
    # All planets on same line.
    # Entire 'list' enclosed in quotes creates a single variable.
    # Why? Whitespace incorporated into the variable.
do
  echo $planet
done

echo; echo "Whoops! Pluto is no longer a planet!"

exit 0

Can anyone show me how can this be done but with a while and an until loop?

You can iterate over an array in a while loop. First we'll need an array though. sh only has 1 -- $@ . Let's use that.

$ set -- Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto
$ while [ $# -gt 0 ]; do echo $1; shift; done
Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune
Pluto

You can do it without shifting as well. Here is another example using an array in bash.

$ declare -a planets=(Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto)
$ i=0; while (( i < ${#planets[@]} )); do echo "${planets}"; ((i++)); done
Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune
Pluto

You can quote either list to see the difference.

while loops while is true or until is false, until loops while is false or until is true.

#!/bin/bash

campaign="on"

while [ "$campaign" == "on" ]; do
	politician="liar"	
	echo "I am a $politician"
	campaign="off"
done

until [ "$campaign" == "on" ]; do
	politician="sucker"
	echo "I am a $politician"
	campaign="on"
done
1 Like

Some more examples, hope they help :slight_smile:

# for loop with a case statement
for planet in Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto;do
	case $planet in
	Earth)	echo "You live here on $planet"
		;;
	Pluto)	echo "$planet is no longer a planet"
		;;
	*)	echo "$planet"
		;;
	esac
done

# while loop with a counter
C=0
MAX=100
printf '\n\n\t%s\n\n' "Current numbers:"
while [[ $C -le $MAX ]];do
	printf '%s' "$C "
	c=$[ $C % 2 ]
	[[ 0 -eq $c ]] && echo "... is an equal number"
	((C++))
done

Since you pass all arguments as a single quote (all planets/words are within the same quotes), it is handled as a single string.
Therefor, there is only 1 entry, holding all the words.

However, passing an array is diffrently, there you should use: "${@}"
Here, the quotes will embrace each single element of the array, eg: a filename with whitespace in its name will remain 'valid'.

Hope this helps