Get PID of a process into a variable

Hi All,

I need to get the PID of a process which i ran in background into a variable

echo $! gives me the PID of last background process but how to get this into a variable so that i can use "wait" command later in the script to make sure that this background process was done

var = `echo $!`
echo $var

this is not working :confused:

could some body please help
thanks in advance
firestar

Hi.

It would work if you removed the spaces around the =

var=`echo $!`
echo $var

But you could just say:

var=$!
1 Like

I think it won't work until you put it like that:

var=`echo ${!}`
echo $var

Couse without "{}" it tries to use ! as bash command. Anyway your second solution is much better :wink:

Hmm. Interesting, but it seems to work fine:

$ bash
$ cat Slp
sleep 3 &
var=`echo $!`
echo var is $var 
ps -ef | grep leep


$ ./Slp
var is 77811
  503 77811 77810   0   0:00.00 ttys001    0:00.00 sleep 3

(but, yes, the command sub isn't neccessary anyway)

Hmmm, maybe it's because I tried that on the command line :slight_smile: so I got something like "bash: !`: event not found". But it seems that it's working as a part of a script.

:eek: you're right.

That's the kind of thing I'd expect from the C-Shell, not bash :smiley: