bash action: BASH WHILE LOOP

bash action: BASH WHILE LOOP


Hello together, After we talked about the for loop in bash (http://infofreund.de/bash-action-bash-for-loop-files) we want to talk today about the while loop.
As against the for-loop, the while loop has not „initial-parameter“. The loop is running, until the given condition is true.
If you want to build an unlimited loop (maybe for a running service in the background), you can set a condition, that will never be true f.e. 1 -ne 0.
If you have problems with some loops or you want create a more complex loop – please ask me. askme@infofreund.de

 

Requirements:
bash 🙂

Let’s start:

i created a folder „testfolder“ for my examples – you have to replace it with your foldername.

1 while-LOOP: creating 10 ascending numbered files in the bash-shell

set i=1 
while [ $i -le 10 ]
do
touch testfile$i
let i=$i+1
done

2 while-LOOP: a simple password prompt for the bash – you will left the loop, if you insert „secret“

password=““

while [ $password != "secret" ]
do
echo -e "Please prompt your password"
read password
done

3 while-LOOP: a simple bash calculator (exit with strg+c because we use an unlimited loop – 1 will never be 0 🙂 )

while [ 1 -ne 0 ]
do
figure_1=""
figure_2=""
echo -n "Please insert figure 1: "
read figure_1
echo -n "please insert figure 2: "
read figure_2
echo "The sum is: " `echo "$figure_1 + $figure_2" | bc`
echo "The product is: " `echo "$figure_1 * $figure_2" | bc`
echo "The difference" is: `echo "$figure_1 - $figure_2" | bc`
echo "The quotient" is: `echo "$figure_1 / $figure_2" | bc -l`
done

Kommentare sind abgeschaltet.