While loop error

I have a while loop in my script that works most times, but has generated an error once that has me a bit confused. I'm using ps to grab the runtime of a backgrounded command, and testing it to maintain the loop.

If I test this on its own, I run into no problems, but during one use of the script I recieved the error: line 293 '[' '14:13' unary operator expected.

scriptRUNTIME=`ps -eo uid,pid,etime | grep $! | awk '{print $3}'` 

while [ $scriptRUNTIME > 0 ] #this was line 293

do
     some stuff
     scriptRUNTIME=`ps -eo uid,pid,etime | grep $! | awk '{print $3}'`
     echo $scriptRUNTIME "minutes elapsed"
done

Would it instead, be better to evaluate this as:

while [ -n $scriptRUNTIME ]

or

while [ $scriptRUNTIME -gt 0 ]

-n is closer to what you want, but a lot of that pipe chaining in backticks is pointless since you know the PID. Just watch if /proc/pid still exists, each running process gets a directory inside /proc/.

# keep looping while the process still exists
while [ -d /proc/$! ]
do
        do stuff
done
1 Like

Try this:

while [ "$scriptRUNTIME" -gt 0 ] #this was line 293

I would use the simpler method of checking /proc, but the directory doesn't exist in OS X.

I'll try -n and see if that resolves the error.
thanks!

I had to check but wow, you're right. Next time someone says OSX is just like any other UNIX underneath I can give them that.

This is why it's always a good idea to say what your system is in your first post, so we don't have to play the strange combination of 20-questions and pin-the-tail-on-the-donkey that is finding answers to questions here. :wink:

Be sure to quote the string. No quotes means [ -n $STUFF ] becomes [ -n ] which is a syntax error. [ -n "$STUFF" ] becomes [ -n "" ] which is okay.