首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我想通过管道将一个脚本的输出传递给不同的脚本,这些脚本将独立处理第一个脚本的输出。

我想通过管道将一个脚本的输出传递给不同的脚本,这些脚本将独立处理第一个脚本的输出。
EN

Stack Overflow用户
提问于 2019-07-09 03:44:00
回答 1查看 113关注 0票数 0

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

我读过很多关于将变量从shell导出到shell的答案,比如使用tty获取shell的名称,然后将第一个终端会话的输出重定向到第二个终端会话,这只在执行单个命令时起作用,但在执行两个脚本的过程中不起作用。

这是第一个脚本:

代码语言:javascript
复制
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

第二个脚本是相同的:

代码语言:javascript
复制
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中,然后让这两个脚本在各自的终端中继续执行。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-10 01:06:20

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

代码语言:javascript
复制
#!/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

第二个中的...and:

代码语言:javascript
复制
#!/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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56941656

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档