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?
[ 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With