Bash - While

About

The while structure in Bash.

Syntax

while true  
do  
    <commands>
done  

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

ls -l | while IFS=" " read -r line; do
    echo Line: $line
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 IFS=" " 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 (From http://askubuntu.com/questions/581265/how-can-i-convert-a-csv-file-to-xml)

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

Powered by ComboStrap