Table of Contents

About

This article is dedicated to the while syntax in Bash.

Example

Sequence

Bash - Sequence

count=0  
while [ $count -le 10 ]  
do  
    echo "$count"
    count=$(( $count + 1 ))
done  

Infinite loop

done=0
while : ; do
  ...
  if [ "$done" -ne 0 ]; then
      break
  fi
done

where:

  • : is the no-op command; its exit status is always 0

Basic

The command:

ls -l | while read -r lineVariable; do
    echo Line: $lineVariable
done
Line: -rw-r--r-- 1 root root 1849173 May 13 2015 unixODBC-2.3.2.tar.gz
Line: -rwxr-xr-- 1 oracle oinstall 64 May 16 2017 whileDemo.sh

Process monitoring

Linux process monitoring (replace pid with your pid)

pid=22018
count=0
while kill -0 $pid 2> /dev/null; do
    count=$(( $count + 1 ))
    echo "${count} - Process is running"
    sleep 10
done
echo "${count} - Process has exited"

Stream / Output parsing

ls -l | while read -r permission child owner group size monthDate dayDate rest; do
    echo Line: 
    echo '    - Permission: '$permission
    echo '    - Child: '$child
    echo '    - Owner: '$owner
    echo '    - Group: '$group
    echo '    - Size: '$size
    echo '    - Month of Date: '$monthDate
    echo '    - Day of Date: '$dayDate
    echo '    - Rest: '$rest
done
Line:
    - Permission: -rw-r--r--
    - Child: 1
    - Owner: root
    - Group: root
    - Size: 1849173
    - Month of Date: May
    - Day of Date: 13
    - Rest: 2015 unixODBC-2.3.2.tar.gz
Line:
    - Permission: -rwxr-xr--
    - Child: 1
    - Owner: oracle
    - Group: oinstall
    - Size: 457
    - Month of Date: May
    - Day of Date: 16
    - Rest: 2017 whileDemo.sh

Csv to Xml

How to converse a Csv to XML 1)

file_in="simple.csv"
file_out="simple.xml"
echo '<?xml version="1.0"?>' > $file_out
echo '<Customers>' >> $file_out
while IFS=$',' read -r -a arry
do
  echo '  <Customer>' >> $file_out
  echo '    <Name>'${arry[0]}'</Name>' >> $file_out
  echo '    <Age>'${arry[1]}'</Age>' >> $file_out
  echo '    <Country>'${arry[2]}'</Country>' >> $file_out
  echo '  </Customer>' >> $file_out
done < $file_in
echo '</Customers>' >> $file_out

Syntax

while list; do list; done

where you can also use the break and continue loop control statement.

  • Exit: The while command continuously executes the do list as long as the last command in list returns an exit status of zero.
  • Exit status: The exit status of the while and until commands is the exit status of the last do list command executed, or zero if none was executed.