From Unique Crow, 3 Months ago, written in Plain Text.
  1.  
  2.  
  3. You can unlink a named pipe immediately after attaching it to the current process, which practically results in an anonymous pipe:
  4.  
  5. # create a temporary named pipe
  6. PIPE=$(mktemp -u)
  7. mkfifo $PIPE
  8. # attach it to file descriptor 3
  9. exec 3<>$PIPE
  10. # unlink the named pipe
  11. rm $PIPE
  12. ...
  13. # anything we write to fd 3 can be read back from it
  14. echo 'Hello world!' >&3
  15. head -n1 <&3
  16. ...
  17. # close the file descriptor when we are finished (optional)
  18. exec 3>&-
  19.  
  20. If you really want to avoid named pipes (e.g. the filesystem is read-only), your "get a grip of the file descriptors" idea also works. Note that this is Linux-specific due to the use of procfs.
  21.  
  22. # start a background pipeline with two processes running forever
  23. tail -f /dev/null | tail -f /dev/null &
  24. # save the process ids
  25. PID2=$!
  26. PID1=$(jobs -p %+)
  27. # hijack the pipe's file descriptors using procfs
  28. exec 3>/proc/$PID1/fd/1 4</proc/$PID2/fd/0
  29. # kill the background processes we no longer need
  30. # (using disown suppresses the 'Terminated' message)
  31. disown $PID2
  32. kill $PID1 $PID2
  33. ...
  34. # anything we write to fd 3 can be read back from fd 4
  35. echo 'Hello world!' >&3
  36. head -n1 <&4
  37. ...
  38. # close the file descriptors when we are finished (optional)
  39. exec 3>&- 4<&-
captcha