I’m writing a routine that will identify if a process stops running and will do something once the processes targeted is gone.
I came up with this code (as a test for my future code):
#!/bin/bash
value="aaa"
ls | grep $value
while [ $? = 0 ];
do
sleep 5
ls | grep $value
echo $?
done;
echo DONE
My problem is that for some reason, the loop never stops and echoes 1 after I delete the file “aaa”.
0
0 >>> I delete the file at that point (in another terminal)
1
1
1
1
.
.
.
I would expect the output to be “DONE” as soon as I delete the file…
What’s the problem?
SOLUTION:
#!/bin/bash
value="aaa"
ls | grep $value
while [ $? = 0 ];
do
sleep 5
ls | grep $value
done;
echo DONE
The value of
$?changes very easily. In the current version of your code, this line:prints the status of the previous command (
grep) — but then it sets$?to 0, the status of theechocommand.Save the value of
$?in another variable, one that won’t be clobbered next time you execute a command:If the
ls | grep aaais intended to check whether a file namedaaaexists, this:is a cleaner way to do it.