Skip to content
Advertisement

I want to pipe the output of one script to different script that will process the output of the first script independently?

I have a very trivial bash script taking input from the user in the first step and then echo an output. I want to run the same script in different shells and let the first shell take input and echo its output and send it to the input of the other shell, and let the both of shells continue executing normally after that.

I have read many answers about exporting variables from shell to shell, like getting the name of the shell using tty and then redirect the output of the first terminal session to the second terminal session, that works only when executing single commands, but not mid executing of the two scripts.

This is the first script:

answer="n"
while [ "$answer" != 'y' ];do
    echo "enter the first value :"
    read first
    echo "the output is: "
    echo 6
    echo "enter value of A:"
    read  A
    echo "do you want to exit"
    read answer
done

The second script is the same:

answer="n"
while [ "$answer" != 'y' ];do
    echo "enter the first value :"
    read first
    echo "the output is: "
    echo 6
    echo "enter value of A:"
    read  A
    echo "do you want to exit"
    read answer
done

I want the first script running in the first terminal to output the number 6 and then pipe the number to the second script to be placed in the variable first and then let the two scripts continue executing in their respective terminals.

Advertisement

Answer

A named pipe is the appropriate tool. Thus, in the first script:

#!/usr/bin/env bash
my_fifo=~/.my_ipc_fifo
mkfifo "$my_fifo" || exit
exec {out_to_fifo}>"$my_fifo" || exit

answer="n"
while [ "$answer" != 'y' ];do
    echo "enter the first value :"
    read first
    echo "the output is: "
    echo 6                          # one copy for the user
    printf '%s' 6 >&$out_to_fifo  # one copy for the other program
    echo "enter value of A:"
    read  A
    printf '%s' "$A" >&$out_to_fifo
    echo "do you want to exit"
    read answer
done

…and in the second:

#!/usr/bin/env bash
my_fifo=~/.my_ipc_fifo
exec {in_from_fifo}<"$my_fifo" || exit  # note that the first one needs to be started first!

while IFS= read -r -d '' first <&"$in_from_fifo"; do
  echo "Read an input value from the other program of: $first"
  read -r -d '' second <&"$in_from_fifo"
  echo "Read another value of: $second"
  read -p "Asking the user, not the FIFO: Do you want to exit? " exit_answer
  case $exit_answer in [Yy]*) exit;; esac
done
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement