0

I have created a basic shell script that simply counts down from 1000. This is just for testing but could be any application/process.

##filename:test.sh##

#!/bin/bash
i=1000; while [ $i -gt 0 ]; do echo $i; i=`expr $i - 1`; sleep 1; done

Which I start running thus:

sh test.sh

I now need to get: a) the pid of that script, b) the state of that script

If I do

pidof sh test.sh 

I get multiple results though.

Running

ps aux | grep test.sh 

I get multiple entries including some that are Terminated (state=T) and one that is grep test.sh. How can I restrict the pidof to just the one(s) I need (assume it is just the one instance that is running)

I also need the state. I tried running:

ps aux | grep test.sh | ps -o stat --no-headers

but that didn't work. I get the state, but for multiple items

1

pidof -x test.sh should give you what you need to get the PID.

From the man page,

-x Scripts too - this causes the program to also return process id's of shells running the named scripts.

Here's my test,

tony@trinity:~$ ls -l testit.sh
-rwxr-xr-x 1 tony tony 83 Jan  5 14:53 testit.sh
tony@trinity:~$ ./testit.sh
1000
999
998
997

meanwhile

tony@trinity:~$ ps -ef | grep testit.sh
tony      4233 20244  0 14:58 pts/5    00:00:00 /bin/bash ./testit.sh
tony      4295  3215  0 14:58 pts/6    00:00:00 grep --color=auto testit.sh

and then

tony@trinity:~$ pidof -x testit.sh
4233

Your later query is a common issue, one solution is,

ps aux | grep test.sh | grep -v grep

which should give you only a single line (assuming test.sh is unique).

And lastly, in your final command, you're not just passing a single PID, you're passing a whole line of text, and that's not how ps expects to be given a PID anyway (it expects the PID after -p).

For example,

tony@trinity:~$ ps aux | grep testit.sh
tony      4233  0.1  0.0   4288  1276 pts/5    S+   14:58   0:00 /bin/bash ./testit.sh
tony      5728  0.0  0.0   3476   760 pts/6    S+   15:04   0:00 grep --color=auto testit.sh

So we need to grep out the grep, and then only return the pid.

tony@trinity:~$ ps aux | grep testit.sh | grep -v grep | awk '{print $2}'
4233

then,

tony@trinity:~$ ps -o stat --no-headers -p $(ps aux | grep testit.sh | grep -v grep | awk '{print $2}')
S+

There are probably plenty of less convoluted ways to get there, but I wanted to show the progress.

  • That's great cheers. good explanation too. – IGGt Jan 5 '16 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.