Bash while Loop
A while loop repeats its commands as long as the condition is true.
Make sure something in the loop changes the condition, or it runs forever.
Count to three
Save this as while.sh:
#!/bin/bash
count=1
while [ $count -le 3 ]; do
echo "Count: $count"
count=$((count + 1))
done
Run it:
./while.sh
Count: 1
Count: 2
Count: 3
Read a file line by line
Save this as lines.sh:
#!/bin/bash
while read -r name; do
echo "Hello, $name"
done < names.txt
Run it:
./lines.sh
Hello, Tove
Hello, Jani
Hello, Linus