Shell While Loops
While Loops
The while loop enables you to execute a set of commands repeatedly until some condition occurs. It is usually used when you need to manipulate the value of a variable repeatedly.
Syntax
while command
do
Statement(s) to be executed if command is true
done
Scripts
while.sh
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
passwd.sh
#!/bin/bash/bin/bash
file=/etc/passwd
set field delimiter to :
read all 7 fields into 7 vars
while IFS=: read -r user enpass uid gid desc home shell
do
# only display if UID >= 500
[ $uid > 250 ] && echo "User $user ($uid) assigned \"$home\" home directory with $shell shell."
done < "$file"
nameserver.sh
#!/bin/bash
file=/etc/resolv.conf
while IFS= read -r line
do
# echo line is stored in $line
echo $line
done < "$file"