It wasn't me. You can't prove anything.


2010-03-26

Watching a process run in BASH

Once you get the process ID you can watch the process with the ps command and do whatever you want in the loop. Most of the time I am waiting for something to complete or looking for a specific thing to happen. Typically you want to do this in order to report progress or enforce a timeout. You cannot trap errors this way, well, you loose track of the error channel. It is all a balance of needs and capabilities.

#!/bin/bash 
sleep 10 # Just kick off a process and wait 10 seconds
processID=$! # Gives you the last backgrounded process ID 
echo -n "running"
while [ -n "`ps -ef | egrep \" $processID \"`" ]; do
 
    echo -n "." 
    sleep 1 
done
echo ""
echo "ID was $processID"

It was so much fun playing around with this and trying to get this basic idea to work in a far more complex script that I missed a meeting. That was kind of cool. Not that I missed the meeting, but hat I was that focused on one task. I get pulled in so many directions at work these days that It was nice to work on one thing for half a day or so.

No comments: