将交互式脚本的标准输出管道传输到它自己的标准输入

piping stdout of an interactive script to its own stdin

考虑以下简单的交互式 shell 脚本:

# tool.sh
echo "Good Morning."
echo "My Name is Mr. Sunshine, I am 100 years old."
echo
echo "So, what's your name?"
read name;
echo "and, whats' your age?"
read age;
echo $name, $age years old > output.txt

也就是说,这个脚本现在应该由另一个脚本以编程方式 运行。就这么简单:

echo -e "Anton\n28" | bash tools.sh

瞧,output.txt 现在包含 "Anton, 28 years old"。

棘手的部分来了:我想在 output.txt 中看到 "Mr. Sunshine, 100 years old",只需打开一次工具。

这里的问题是管道的设置,该管道解析工具的输出并直接将部分发送到其输入

解析可以这样进行:

sed -nr 's/^My Name is (.*), I am (.*) years old\.$/\t/p'

您可以为此使用命名管道。

mkfifo tools_pipe
cat tools_pipe \
    | ./tools.sh \
    | sed -rnu 's/My Name is (.*), I am (.*) years old\./\n/p' \
    > tools_pipe
rm tools_pipe # cleanup

命名管道基本上是一个文件,您可以同步读取和写入。 要将工具的输出作为输入提供给工具本身,可以使用命名管道来建立此循环连接。