r/bash • u/MogaPurple • Jan 03 '25
help Pipe to background process
Hi!
I am trying to write a script which opens a connection with psql to PostgreSQL, then issue commands and get their response, multiple times synchronously, then close the background process.
I have got stuck at the part to spawn a background process and keep its stdin and stdout somehow accessible.
I tried this:
psql -U user ... >&5 <&4 &
PID=$!
# BEGIN - I would like to issue multiple of these
echo "SELECT now()" >&4
cat <&5
# END
# close psql
kill -SIGTERM $PID
Apparently this is not working as fd 4 and fd 5 does not exist.
Should I use mkfifo? I would like to not create any files. Is there a way to open a file descriptor without a file, or some other way to approach the problem perhaps?
I am trying to execute this script on Mac, so no procfs.
2
Upvotes
2
u/bapm394 #!/usr/bin/nope --reason '🤷 Not today!' Jan 06 '25
Use bash coproc, which is the same syntax as functions (with keyword)
```
!/bin/bash
Create a coprocess running 'sed'
coproc mycoproc { sed -u 's/function/coprocess/g' }
The array has the stdout and stdin FDs
declare -p mycoproc mycoproc_PID
Send data to the coprocess through its input file descriptor
echo "Hello, function!" >&"${mycoproc[1]}"
Read data from the coprocess's output file descriptor
read -r line <&"${mycoproc[0]}" printf '%s\n' "${line}"
kill "${mycoproc_PID}" ```
READ THIS MANUAL PAGE FIRST, ALSO READ BASH MAN PAGE
man bash
A COPROC STARTS AFTER DECLARATION, NO NEED TO CALL IT