我有一个非常简单的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中,然后让这两个脚本在各自的终端中继续执行。
发布于 2019-07-10 01:06:20
命名管道是合适的工具。因此,在第一个脚本中:
#!/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:
#!/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
donehttps://stackoverflow.com/questions/56941656
复制相似问题