Obtaining PID of command earlier in Pipeline

In a pipeline, all processes are started concurrently, there's not one that is earlier than the others.

You could do:

(echo "$BASHPID" > pid-file; exec inotifywait -m ...) | while IFS= read -r...

Or portably:

sh -c 'echo "$$" > pid-file; exec inotifywait -m ...' | while IFS= read -r...

Also note that when the subshell that runs the while loop terminates, inotifywait would be killed automatically the next time it writes something to stdout.


If you need the process ID in the loop, print it first.

sh -c 'echo "$$"; exec inotifywait -m ...' | {
  read inotifywait_pid
  while IFS= read -r f; do
    …
    if …; then kill "$inotifywait_pid"; break;
  done
}

Tags:

Bash

Pipe

Pid