17 While loop - kumar159man/MyShellLearning GitHub Wiki

While loop

infinite while loop

#!/usr/bin/bash
while true
do
  echo "This is an infinite loop"
done

Another way

#!/usr/bin/bash
while :
do
  echo "This is an infinite loop"
done

while loop with commands

#!/usr/bin/bash

while i=$(whoami)
do
  echo $i
done

This is also an infinite loop it will keep on executing

while loop with some condition

#!/usr/bin/bash i=1 while $i -le 10 do echo $i (( i++ )) done

while loop to read a file

#!/usr/bin/bash
while read file
do
  echo $file
done < file.txt
  • Output
myubuntu@myubuntu-VirtualBox:~/Desktop/shellScripts$ ./while2.sh 
This is first line
This is second line
This is third line
This is fourth line
  • File content
myubuntu@myubuntu-VirtualBox:~/Desktop/shellScripts$ cat file.txt 
This is first line
This is second line
This is third line
This is fourth line
  • Reading a file another way
#!/usr/bin/bash
cat file.txt |while read file
do
  echo $file
done

while with IFS

By default IFS(Internal Field Separator) is space Let's work on this file

myubuntu@myubuntu-VirtualBox:~/Desktop/shellScripts$ cat inventory.txt 
3.129.21.117 myuser date
18.220.89.137 myubuntu whoami

Shell script

#!/usr/bin/bash
cat inventory.txt | while read f1 f2 f3
do
   echo $f1
   echo $f2
   echo $f3
done

Output

myubuntu@myubuntu-VirtualBox:~/Desktop/shellScripts$ ./while3.sh 
3.129.21.117
myuser
date
18.220.89.137
myubuntu
whoami

In the above file separator was a space. Now let's work on comma separated file

myubuntu@myubuntu-VirtualBox:~/Desktop/shellScripts$ cat inventory.txt 
3.129.21.117,myuser,date
18.220.89.137,myubuntu,whoami
#!/usr/bin/bash
cat inventory.txt | while read f1 f2 f3
do
   echo $f1
   echo $f2
   echo $f3
done
myubuntu@myubuntu-VirtualBox:~/Desktop/shellScripts$ ./while3.sh 
3.129.21.117,myuser,date


18.220.89.137,myubuntu,whoami

field is not identified so all the lines gets displayed

#!/usr/bin/bash
cat inventory.txt | while IFS="," read f1 f2 f3
do
   echo $f1
   echo $f2
   echo $f3
done
unset IFS
myubuntu@myubuntu-VirtualBox:~/Desktop/shellScripts$ ./while3.sh 
3.129.21.117
myuser
date
18.220.89.137
myubuntu
whoami

unset IFS will leave the IFS to default

If you see the file consist of 3 fields if we try to get 2 fields then the second field gets clubbed with 3 field

#!/usr/bin/bash
cat inventory.txt | while IFS="," read f1 f2
do
   echo $f1
   echo $f2
done
unset IFS

Output

myubuntu@myubuntu-VirtualBox:~/Desktop/shellScripts$ ./while3.sh 
3.129.21.117
myuser,date
18.220.89.137
myubuntu,whoami
⚠️ **GitHub.com Fallback** ⚠️