0

In my script, I am executing cat, then trying to grep to get the process id.

I used this :

ps | grep -e \'cat$\' | cut -d\' \' -f2 | head -n 1

but it's not returning anything.

Joni
  • 108,737
  • 14
  • 143
  • 193
Subhash
  • 568
  • 1
  • 5
  • 21
  • How are you executing `cat`? There is probably a more direct way to get the PID than by listing processes. – Joni Mar 29 '13 at 11:57
  • Are the two commands running in sequence? If you're executing cat, waiting for it to finish and then using ps, then there won't be a PID to find. – chooban Mar 29 '13 at 12:00
  • Try : ps | grep -e 'cat$' | cut -d ' ' -f2 | head -n 1 . Hint: check your chain of pipes step by step to see if the results are as you expect. – katastrophos Mar 29 '13 at 12:04
  • To get the PID in a Perl script you can use the `$$` special variable. – amon Mar 29 '13 at 12:15
  • 1
    So you are not using `perl`? – Joni Mar 29 '13 at 12:29
  • @Joni and chooban: i will running cat in background, like 'cat &' then grep it – Subhash Mar 29 '13 at 12:29
  • [spam] If you want to just `kill` the `cat`, try using the command `curiosity`, that is supposed to kill cats ;-) – anishsane Mar 30 '13 at 06:48

1 Answers1

1

When you start a background process in a shell with program & you can access the PID of the child process through $!.

For example:

bash-4.2.37$ cat &
[1] 9664
bash-4.2.37$ CAT_PID=$!
...time passes...
bash-4.2.37$ echo $CAT_PID
9664
Joni
  • 108,737
  • 14
  • 143
  • 193