重定向到一个使用devtty的脚本。

问题描述 投票:0回答:1

我正在写一个可能需要人工输入的git钩子。根据 本回答 要用 exec < /dev/tty 的脚本中。这样就完成了任务,但现在没有可能将标准输出重定向到那个钩子上(为了测试目的)。我想问题可以归结为一个问题:如何将消息发送到 /dev/tty 的方式让另一个进程读取它?不知道这是否可能。

这里是最小的可重复的例子。

# file: target.sh

exec < /dev/tty # we want to use /dev/tty
read -p  "Type a message: " message
echo "The message ${message}"

我试了几个类似的解决方案

echo -e "foo\n"| tee /dev/tty | source target.sh

它实际上在控制台中打印出了信息,就在这之后 read 促使,但 message 变量仍未设置。有什么办法可以解决这个问题吗?

bash stdout githooks tty bats-core
1个回答
1
投票

你可以使用 expect 来实现结果。

#!/bin/bash

expect << EOF
spawn bash target.sh
expect {
    "Type a message: " {send "foo\r"; interact}
}
EOF

2
投票

你可以把输入文件作为一个可选的参数:

#!/bin/bash

input_file=${1:-/dev/tty}
read -p  "Type a message: " message < "${input_file}"
echo "The message ${message}"

# other stuff ...

现在测试一下这个命令,就像这样

your_script
your_script <(echo foo)
some_cmd | your_script
some_cmd | your_script <(echo foo)

PS: 语法是 <(echo foo) 我使用的是一个所谓的 工艺替代.

© www.soinside.com 2019 - 2024. All rights reserved.