Thursday, 25 December 2014

Shell script with a Progress Indicator

Hi,

    Shell script is a powerful tool for system administrators to make their life easy. It's Potential are numerous, below is a simple shell script that shows how to control a background function from the main script and show a progress indicator until the main script is complete. It's a basic script i want to post here for my reference and also for anyone who just need a little push to start their scripting, you can expand/improvise this script as per your need.


#!/bin/bash

#script to print twirling lines

#function to print rotating lines continuously

function rotate_line
{

INTERVAL=1
T_COUNT=0

while :
do
        T_COUNT=$(expr $T_COUNT + 1)
        case $T_COUNT in
                1) echo -e "-----\b\b\b\b\b\c"
                   sleep $INTERVAL
                   ;;
                2) echo -e '\\\\\\'"\b\b\b\c"
                   sleep $INTERVAL
                   ;;
                3) echo -e "|||||\b\b\b\b\b\c"
                   sleep $INTERVAL
                   ;;
                4) echo -e "/////\b\b\b\b\b\c"
                   sleep $INTERVAL
                   ;;
                *) T_COUNT=0
                   ;;
        esac
done

}

#function to exit the rotate_line function in case of interruption to the main script, please note that kill -9 can't be trapped , so if a kill -9 is passed to the main script,
#the rotate_line function will keep running and had to be killed manually

function trap_exit
{
    kill -9 $ROTATE_PID
}

# Main script
#call the trap_exit function for the interrupt code 1, 2, 3, 15 and exit with the status code 2, note that without the below statement, the interruption of main script will make #the rotate_line process orphan and running forever until manually interrupted. However kill -9 can't trapped


trap 'trap_exit; exit 2' exit 1 2 3 15

#call the rotate_line function in background


rotate_line &

#Record the process id of the rotate_line function
ROTATE_PID=$!

TOTAL_COUNT=300

#loop through for 5 minutes and rotating lines will be displayed for this 5 minutes
until (( TOTAL_COUNT == 0 ))
do
        (( TOTAL_COUNT = TOTAL_COUNT - 1 ))
        sleep 1
done


#Once the loop is completed , terminate the rotate_line function
kill -9 $ROTATE_PID


No comments:

Post a Comment