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
}

Friday, April 25, 2014

How To: Python LDIF package stops parsing upon error - how to get around this

Python LDIF package stops when user dn does not meet internal regex for dn. While this is great, the problem is when you just want to get the record - good or bad for other purposes than to push it into LDAP etc.
It is simple to override the 'is_dn' method used by the ldif package by setting the package method like so:
import ldif

def is_dn(s):
    return 1

ldif.is_dn=is_dn
 
That is it. From this point on ldif package will use the new is_dn() method and will not fail on invalid dns.