How to use "coproc" to interact with another command-driven program

Well, obviously, I am NOT a bash guru and need one!

I have never used coproc before, but it seems to me that this is exactly what I need. But I have to admit that I cannot extrapolate from various ping examples! [I tried a couple of hours ...]

All I want to do is run the "coproc" script shell, which can take input from standard input and write the results to the standard version. I want the main script to send and process these commands and results accordingly.

Here is one of the simplest essays of what I'm trying to do: IMAGE WITH BEST DETAILS

#! /bin/bash coproc bkgndProc { /some/path/to/usefulScript.sh maybeSomeArgsHere } // send command #1 to bkgndProc here result=$(echo 'command' <&${bkgndProc[0]}) ### Doesn't work for me echo "Did it work? $result" ### this just prints back the 'command' I used // here execute conditional logic based on result: // if result1; then // send command #2 here, getting results // else // send command #3 here, again getting results // fi 

Sorry to use the pseudo code above, but I'm not sure what these send commands should do! If anyone can provide details that would be greatly appreciated!

+6
source share
1 answer
 result = $(echo 'command' <&${bkgndProc[0]}) ### Doesn't work for me 

will not work, at least basically, since it has spaces

 result=$(echo 'command' <&${bkgndProc[0]}) 

---- Update ----

A simple concept can be shown in a script as follows:

 #!/bin/bash # create the co-process coproc myproc { bash } # send a command to it (echo a) echo 'echo a' >&"${myproc[1]}" # read a line from its output read line <&"${myproc[0]}" # show the line echo "$line" 

Outputs:

 a 

Another that reads multiple lines using a timeout:

 #!/bin/bash coproc myproc { bash } # send a command to message 4 random numbers in 4 lines echo 'echo "$RANDOM"; echo "$RANDOM"; echo "$RANDOM"; echo "$RANDOM"' >&"${myproc[1]}" # keep reading the line until it times out while read -t 1 -u "${myproc[0]}" line; do echo "$line" done 

Output:

 17393 1423 8368 1782 

If we use cat , it will no longer go away, since the other end is still alive and connected, and EOF has not yet been reached. This is the reason we used timeouts.

 cat <&"${myproc[0]}" 
+5
source

Source: https://habr.com/ru/post/953585/


All Articles