Reputation: 97
I have a function in a bash script that I want to return true if a process is running and false if not. The code for my function is:
checkProcess() {
if [ kill -s 0 $(getPid) > /dev/null 2>&1 ]; then
return 0
else
return 1
fi
}
When I use this function it does not seem to work. I use it like so:
if [ ! checkProcess ]; then
#do something, like rm file containing PID
fi
However if I just use the below implementation it works fine:
if [ ! kill -s 0 $(getPid) > /dev/null 2>&1 ]; then
#do something, like rm file containing PID
fi
Is there a reason for this? Am I not returning the correct values in my function? Or is it all just wrongly implemented?
Upvotes: 3
Views: 3995
Reputation: 74596
[
is not syntax; it is a command. It is commonly used with if
, which works based on its return code.
To directly check the return code of a different command, e.g. kill
, you should remove the [
and ]
(the last argument to [
):
if kill -s 0 $(getPid) &>/dev/null; then
# ...
fi
Note that &>
is a Bash extension, equivalent to >/dev/null 2>&1
.
Upvotes: 8