Abner Ballardo

This week was the second preliminary laboratory of Operating Systems course in the PUCP. One topic I had to explain to the students was a little introduction to shell scripting.

I told them about an application I made using only Bash Shell Scripting. Why did I use shell scripting? well, because that application had to take a big amount of data (more than 4GB) from two differents databases (oracle & mysql) and do a complex bussiness logic. The solution I provided was filtering the input data with some simple rules (using awk & sed) and discarded unuseful data (aprox 40%). After that, the application used some temporary tables (to do the complex logic) on mysql and got the expected result. It was unncessary to make a compiled program.

BTW, we can do some interesting things with Shell Scripting. For example, a good practice is to give users a feedback that a script is not hung (progress indicator). This is specially useful with long time jobs.

I will show two kinds of progress indicators:

Simple Progress Indicator

Print a sequence of dots.

#!/bin/bash
#
# Copyright © Abner Ballardo Urco
# http://www.modlost.net
#

#
# Simple Progress Indicator
#
function simple_progress_ind {
  # Sleep at least 1 second otherwise this algoritm will consume
  # a lot system resources.
  interval=1

  while true
  do
    echo -ne "."
    sleep $interval
  done
}

#
# Stop distraction
#
function stop_progress_ind {
  exec 2>/dev/null
  kill $1
  echo -en "\n"
}

echo "Simple Progress Indicator"
echo -n "Processing "

simple_progress_ind &
pid=$!

# Thanks Stephen Concannon for sending this fix.
# If the main script is interrupted, this line takes care
# of stopping the progress indicator
trap "stop_progress_ind $pid; exit" INT TERM EXIT

/long/time/job/zzZZzz.sh

stop_progress_ind $pid

Cool Progress Indicator

Print a rotating line.

#!/bin/bash
#
# Copyright © Abner Ballardo Urco
# http://www.modlost.net
#

#
# Cool Progress Indicator
#
function cool_progress_ind {
  chars=( "-" "\\" "|" "/" )
  interval=1
  count=0

  while true
  do
    pos=$(($count % 4))

    echo -en "\b${chars[$pos]}"

    count=$(($count + 1))
    sleep $interval
  done
}

#
# Stop progress indicator
#
function stop_progress_ind {
  exec 2>/dev/null
  kill $1
  echo -en "\n"
}

echo "Cool Progress Indicator"
echo -n "Processing "

cool_progress_ind &
pid=$!

# Thanks Stephen Concannon for sending this fix.
# If the main script is interrupted, this line takes care
# of stopping the progress indicator
trap "stop_progress_ind $pid; exit" INT TERM EXIT

/long/time/job/zzZZZzz.sh

stop_progress_ind $pid