我想将一个脚本的输出传递到另一个脚本,该脚本将独立处理第一个脚本的输出?

时间:2019-07-08 19:43:59

标签: linux bash shell ubuntu unix

我有一个非常简单的bash脚本,第一步是从用户那里获取输入,然后回显输出。我想在不同的shell中运行相同的脚本,并让第一个shell接受输入并回显其输出,并将其发送到另一个shell的输入,然后让这两个shell继续正常执行。

我已经阅读了许多有关将变量从shell导出到shell的答案,例如使用tty获取shell的名称,然后将第一个终端会话的输出重定向到第二个终端会话,这仅在执行单个命令时有效,但是不在两个脚本执行的中间。

这是第一个脚本:

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

第二个脚本相同:

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

我希望在第一个终端中运行的第一个脚本输出数字6,然后将该数字传递到要放置在变量first中的第二个脚本中,然后让这两个脚本继续执行在各自的终端中。

1 个答案:

答案 0 :(得分:1)

命名管道是合适的工具。因此,在第一个脚本中:

#!/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\0' 6 >&$out_to_fifo  # one copy for the other program
    echo "enter value of A:"
    read  A
    printf '%s\0' "$A" >&$out_to_fifo
    echo "do you want to exit"
    read answer
done

...以及第二个:

#!/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