首页 > 解决方案 > 有没有办法“回响”到标准输出什么被重定向为标准输入到程序(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,但是有没有办法不更改现有程序?

标签: linuxunixredirectechoshow

解决方案


这将取决于您的程序。我找到了程序的窍门

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}"

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


推荐阅读