1

I am playing with the coproc of Bash and I am failing to understand something.

I started with the following example:

Example#1

$ coproc MY_BASH { bash; }
[1] 95244
$ echo 'ls -l; echo EOD' >&"${MY_BASH[1]}"
$ is_done=false; while [[ "$is_done" != "true" ]]; do
>   read var <&"${MY_BASH[0]}"
>   if [[ $var == "EOD" ]]; then
>      is_done="true"
>   else
>      echo $var
>   fi
> done
total 0
-rw-rw-r-- 1 username username 0 Nov 11 13:00 file10.txt
-rw-rw-r-- 1 username username 0 Nov 11 13:00 file1.txt
-rw-rw-r-- 1 username username 0 Nov 11 13:00 file2.txt
-rw-rw-r-- 1 username username 0 Nov 11 13:00 file3.txt
-rw-rw-r-- 1 username username 0 Nov 11 13:00 file4.txt
-rw-rw-r-- 1 username username 0 Nov 11 13:00 file5.txt
-rw-rw-r-- 1 username username 0 Nov 11 13:00 file6.txt
-rw-rw-r-- 1 username username 0 Nov 11 13:00 file7.txt
-rw-rw-r-- 1 username username 0 Nov 11 13:00 file8.txt
-rw-rw-r-- 1 username username 0 Nov 11 13:00 file9.txt
$ 

Here we can see that the current Bash shell is able to create a coprocess and interact with it.

Example 2

In this case, I switch from a bash coprocess to a python coprocess:

$ coproc MY_BASH { python; }
[1] 95244
$ echo 'print("hello"); print("EOD");' >&"${MY_BASH[1]}"
$ is_done=false; while [[ "$is_done" != "true" ]]; do
>   read var <&"${MY_BASH[0]}"
>   if [[ $var == "EOD" ]]; then
>      is_done="true"
>   else
>      echo $var
>   fi
> done

In this scenario the program hangs and gets blocked.

I have the impression that I am forgetting to send something in the input.

Any help to better understand what is going on will be appreciated.

1 Answer 1

1

There are a couple of problems here…

First, you need to use the -i option of Python so that it enters interactive mode and reads commands from stdin for execution. So:

coproc MY_BASH { python -i ; }

Next, Python does not delimit commands with semicolons, so you need to use newlines to separate your commands:

echo $'print("Hello, World!")\nprint("EOD")' >&"${MY_BASH[1]}"
1
  • 1
    Hey @GregBarret! Thanks a lot for your answer, in fact there were several problems. The first one was that the command I tried to use, python didn't exist in my system (maybe because a recent update), so I needed to use one available python3.10 in my case. Once I noticed it, I did the modifications you suggested (replacing the semicolons with newlines and added the -i flag) and it worked perfectly. Thanks a lot Greg! Commented May 5, 2023 at 4:13

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.