4

I'm trying to capture the pid of a background process run in bash.

I tried

somecommand & > somecommand.pid

It outputs the pid to the screen but it's not part of stdout of the command.

[1] 1778
rwilliams
  • 21,188
  • 6
  • 49
  • 55

1 Answers1

7

The special variable $! contains the PID of the most recent job placed in the background:

$ sleep 4 &
$ sleep_pid=$!
$ echo $sleep_pid
4456

This is documented in Special Parameters of man bash

builder-7000
  • 7,131
  • 3
  • 19
  • 43