有没有一种方法可以"回显"标准输出被重定向为标准到程序(Unix)的内容?



假设我有一个程序可以从控制台获取有关用户的信息。

$ ./program
Enter your name : Foo
Enter your phone number : Bar
Your name is Foo and phone number Bar.

现在,如果我不想手动输入"Foo"和"Bar",而是想从文件中重定向输入......

输入文件.txt

Foo  
Bar

这就是输出发生的情况...

$ ./program < inputfile.txt
Enter your name : 
Enter your phone number : 
Your name is Foo and phone number Bar.

通过重定向,您无法看到冒号后输入的内容。有没有办法使输入在控制台上可见(如第一个示例(?

编辑 :这基本上与此线程提出的问题相同: https://unix.stackexchange.com/questions/228954/c-how-to-redirect-from-a-file-to-cin-and-display-as-if-user-typed-the-input

但是我只找到了有关更改程序和添加功能isatty的建议,但是有没有办法不更改现有程序?

这取决于你的程序。我找到了该程序的技巧

printf "%s : " "Enter your name"
read  name
printf "%s : " "Enter your phone number"
read  phone
echo "Your name is ${name} and phone number ${phone}"

在这里你可以使用

while read -r line; do
sleep 1
echo "${line}"
done < inputfile.txt | tee >(./program)

当程序更改为

read -p "Enter your name : " name
read -p "Enter your phone number : " phone
echo "Your name is ${name} and phone number ${phone}"

因此,您可以测试此解决方案并希望得到最好的结果。

tee /dev/tty < inputfile.txt | program将回显文件的内容,但它不会与您的提示匹配。它看起来像

$ tee /dev/tty < inputfile.txt | ./program
Foo
Bar
Enter your name : 
Enter your phone number : 
Your name is Foo and phone number Bar.

我认为没有办法让所有东西都像你想要的那样对齐。

最新更新