A command which returns either a process ID, if running, or some other output if not?
Solution 1
Finding PID's
There are other tools rather than ps
for looking up processes based on their names.
$ pgrep name
Example
$ sleep 100 &
[1] 2556
$ pgrep sleep
2556
Above we can see the process named sleep
is started and then backgrounded. If we use pgrep
to look for processes with that name we get back its PID.
Checking status
As to your question about the output being blank. When commands return they'll often times return a status code that gets stored in a special variable, $?
in Bourne shells, such as Bash. So you simply need to interrogate this variable's contents to find out if the process name you were looking for was present or not.
Example
Similar example using sleep
again.
$ sleep 100 &
[1] 3228
Look for the PID of a process named sleep
.
$ pgrep sleep
3228
Check its status variable, $?
, a zero means it ran successfully, and found what we were looking for.
$ echo $?
0
Now if we look for a bogus process named sleepy
.
$ pgrep sleepy
Not only do we get no output, but the status variable has a one in it, denoting that the command we ran, was unsuccessful in finding what we were looking for.
$ echo $?
1
Solution 2
You can combine commands as follows:
ps <pid> || echo "message"
If the pid exist you will get pid else you will get message printed.
Related videos on Youtube
![MongoLearner](https://i.stack.imgur.com/kzwDV.jpg?s=256&g=1)
MongoLearner
Updated on September 18, 2022Comments
-
MongoLearner almost 2 years
I'm looking for a command that will give me the PID, and it's not running it should give me some output other than blank.
In my program, sometimes the library I'm using gives blank output even if that process is running and I'm not able to detect whether the blank output is due to the libray or due to the process having stopped!
Changing the library call will take time, so I'm looking for suggestions of such a shell command as workaround?
-
MongoLearner over 10 yearsi got the idea.. but i dont know pid, i want to get it ..i know process name
-
MongoLearner over 10 yearshi again, i have tried with pgrep <process> || echo "message" and its working ..simple .thanks a lot