Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I want to have a shell script like this:

my-app &
echo $my-app-pid

But I do not know how the get the pid of the just executed command.

I know I can just use the jobs -p my-app command to grep the pid. But if I want to execute the shell multiple times, this method will not work. Because the jobspec is ambiguous.

share|improve this question

2 Answers 2

up vote 32 down vote accepted

It is in the ! shell variable:

my-app &
echo $!
share|improve this answer
    
It is printing pid as for eg. [1] 893 . I want only number. –  user3153014 Sep 4 at 11:47
    
It should be noted that this stands for programs started in the background. If no background processes have been started the parameter is not set. –  ramrunner Nov 17 at 21:52

Try something like this:

 ps ef | grep [m]y-app | awk '{print $2}'

Placing the first letter of your process between "[]" makes sure you do not get the "grep" process in your list. If needed you can also add a grep on your username.

share|improve this answer
2  
That's very fragile at best and doesn't work if my-app is executed more than once - davidshen84 specifically worries about that cas. –  Mat Jan 30 '12 at 12:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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