LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Check if program is running (https://www.linuxquestions.org/questions/programming-9/check-if-program-is-running-383958/)

Conjurer 11-17-2005 05:58 AM

Check if program is running
 
Hi!

I'm just starting to look into shell scripts. I would like to know if there is a CLI way of checking whether or not a program is running (something along the lines of 'thisCommand -kaffeine' returning a boolean value)?

Y0jiMb0 11-17-2005 06:17 AM

Hi,
I cannot remember a more elegant way (sure some guru around here can provide us with a fascinating solution); but this does the trick:
Code:

some_variable=`ps -C kaffeine|grep -v PID`
then if "some_variable" is empty, kaffeine is not running; if "some_variable" is not empty, kaffeine is running.
It could be that there is an option in "ps" doing exactly what you look for; do "man ps" and have fun reading it.

Regards

edit: or more transparent: substitute "grep -v PID" by "grep kaffeine"

Conjurer 11-17-2005 11:24 AM

I'm not particularly knowledgable on the matter - only started looking into it a few days ago - but aren't you supposed to 'enclose' the ps pipe grep command into a variable on its own?

Like
Code:

a=$(ps -C | grep kaffeine)
- or what? That's the only way I can make it work, anyway. Don't know if I'm missing something.

shanenin 11-17-2005 11:47 AM

both of those examples are called command subtitution. Either one can be used. you can either put the command in backticks
Code:

`enter command here`
or the way you did it
Code:

$(enter command here)
the second method is prefered, it allows for nesting, and possible some other advantages

Conjurer 11-17-2005 12:07 PM

OK - so I've got that little part working - and I've discovered the wonderful 'if grep' construct :) Just one more question:

How would I go about picking up exit values (0 or 1) and variables from other scripts?

shanenin 11-17-2005 12:18 PM

the special variable $? gives the return value of the last command executed
Code:

cat filename | grep hhh
if [ "$?" -eq 0 ]; then
    echo "it found the string"
fi


I have not used bash for a while, I think that is the correct syntax

Conjurer 11-17-2005 01:21 PM

There isn't any way getting the return value of one specific script?

shanenin 11-17-2005 01:26 PM

lets say you have a script called script.sh
Code:

script.sh
echo $?

the variable $? will tell you the return value of the script script.sh

Is that what you are asking?

Conjurer 11-17-2005 01:37 PM

I suppose I was thinking java style (thisFile.myVar) - but it isn't important, as I can easily accomplish what I want using this more sequential approach.


All times are GMT -5. The time now is 08:36 AM.