【问题标题】:I want to pipe the output of one script to different script that will process the output of the first script independently?我想将一个脚本的输出通过管道传输到将独立处理第一个脚本的输出的不同脚本?
【发布时间】:2019-07-08 19:43:59
【问题描述】:

我有一个非常简单的 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 中,然后让这两个脚本继续在各自的终端中执行.

【问题讨论】:

  • “另一个外壳”到底是什么意思?
  • 你说的是RPC机制。存在对 shell 有用的那些——命名管道是构建它们的有用构造——但通常,你最好花时间想一种方法来实现你的目标,而不需要这样的要求。
  • 是的,如果您要谈论“第二个外壳”,那么您向我们展示的 minimal reproducible example 实际上需要有两个外壳
  • @SeanBright 就像我有两个终端同时运行
  • @CharlesDuffy 是的,我尝试制作 fifo 管道,但无法让它们工作。我刚开始和我的教授一起实习,两天来我一直在学习 stackoverflow 和 bash 教科书。但我必须这样做

标签: linux bash shell ubuntu unix


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多