Q:

while loop bash

while true;
do
	#code
done
8
# The syntax is as follows:

while [ condition ]
do
   command1
   command2
   command3
done

# command1 to command3 will be executed repeatedly till condition is true. The argument for a while loop can be any boolean expression. Infinite loops occur when the conditional never evaluates to false. Here is the while loop one-liner syntax:

while [ condition ]; do commands; done
while control-command; do COMMANDS; done

# For example following while loop will print welcome 5 times on screen:

#!/bin/bash
x=1
while [ $x -le 5 ]
do
  echo "Welcome $x times"
  x=$(( $x + 1 ))
done

# And here is above code as a bash while one liner:
x=1; while [ $x -le 5 ]; do echo "Welcome $x times" $(( x++ )); done

# Here is a sample shell code to calculate factorial using while loop:

#!/bin/bash
counter=$1
factorial=1
while [ $counter -gt 0 ]
do
   factorial=$(( $factorial * $counter ))
   counter=$(( $counter - 1 ))
done
echo $factorial


# To run just type:
$ chmod +x script.sh
$ ./script.sh 5
1
while true;
do
	#code
;done
2
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
0

New to Communities?

Join the community