Wednesday, April 30, 2014

Shell script to show progress of process

Shell script progress

Okay, I know, it is gimmicky and it certainly is. But I get tired of not being able to see long running process with some progress indicator. Then you are using commands like 'watch' and running 'tail' this that and the other thing.

So, this little snippet shows a spinning char animation of | / - | - \  in sequence. Yes it is ultra dumb but it keeps me amused :)
This is to be customized to your needs. (this particular code counts user records being exported in an ldapsearch): 
   cnt=`grep -c "dn" $ldiffile`
Line #20 is what does the display and shows $cnt value and a rotating-feel-good blip.
I also don't have a time out if the process goes haywire.

Calling script looks something like:
<background someprocess> &
pid=`jobs -p %%`
progscript="grep -c \"someword\" procoutputfile"
showprog $pid $progscript
The function to show the progress is as follows:
function showprog(){
pid=$1
prog=$2

blip="|"
while ps -p $pid >/dev/null
do
    cnt=`eval $prog`
    if [ "$blip" = "|" ]
    then
        blip="/"
    elif [ "$blip" = "/" ]
    then
        blip="-"
    elif [ "$blip" = "-" ]
    then
        blip="\\"
    elif [ "$blip" = "\\" ]
    then
        blip="|"
    fi
    echo -en "\r$cnt$blip"
sleep 2
done
echo
}

No comments:

Post a Comment