while loops in shell code example
Example 1: while loop bash
while true;
do
done
Example 2: while loop shell script
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
Example 3: shell script:while done
while [ condition ]
do
command1
command2
command3
done
while [ condition ]; do commands; done
while control-command; do COMMANDS; done
x=1
while [ $x -le 5 ]
do
echo "Welcome $x times"
x=$(( $x + 1 ))
done
x=1; while [ $x -le 5 ]; do echo "Welcome $x times" $(( x++ )); done
counter=$1
factorial=1
while [ $counter -gt 0 ]
do
factorial=$(( $factorial * $counter ))
counter=$(( $counter - 1 ))
done
echo $factorial
$ chmod +x script.sh
$ ./script.sh 5
Example 4: linux while loop
while true;
do
;done
Example 5: for while bash
Use for in bash for iterating words in a string or values in an array as:
for value in {1, 2, 3}; do echo $value; done
for value in $(cat arguments_files.txt); do [some_command]; done
And use while for iterating lines from a pipe output as:
cat arguments_file.txt | while read line; do [some_command]; done