在 bourne 脚本中重定向 stdin 后获取用户输入 [英] Getting user input after stdin has been redirected, in a bourne script
问题描述
(这是一个更大的家庭作业的间接部分)
我有类似的东西
<前>在阅读 LINE 时做完成到$LINEecho "请输入:"读取输入完成到$INPUT完成< infile我找不到使用控制台/默认标准输入而不是重定向标准输入进行第二次读取的成功方法.
需要是纯伯恩脚本.
我相信 Bourne shell 支持这一点:
exec 3
在文件和用户之间交替输入.事实上,这将是从文件中发出一系列提示的一种巧妙方式.
这会将文件infile"重定向到第 3 个文件描述符,第一个 read
从中获取其输入.文件描述符 0 是 stdin
,1 是 stdout
,2 是 stderr
.您可以将其他 FD 与它们一起使用.
我已经在 Bash 和 Dash 上对此进行了测试(在我的系统上,sh 符号链接到 dash).
当然有效.还有一些更有趣的:
exec 3
这会交替打印两个文件的内容,丢弃较长文件的多余行.
ONE:doc1的红色第一行二:doc2的蓝色第一行颜色:红色和蓝色ONE:doc1的绿色第二行二:doc2的黄色第二行颜色:绿色和黄色
Doc1 只有两行.doc2 的第三行及后续行被丢弃.
(this is indirectly a part of a much larger homework assignment)
I have something like
while read LINE do stuff-done-to-$LINE echo "Enter input:" read INPUT stuff-done-to-$INPUT done < infile
I can't find a successful way of using the console/default stdin for the second read, instead of the redirected stdin.
Needs to be pure bourne script.
I believe this is supported in the Bourne shell:
exec 3<doc.txt
while read LINE <&3
do
stuff-done-to-$LINE
# the next two lines could be replaced by: read -p "Enter input: " INPUT
echo "Enter input:"
read INPUT
stuff-done-to-$INPUT
done < infile
Input is alternated between the file and the user. In fact, this would be a neat way to issue a series of prompts from a file.
This redirects the file "infile" to the file descriptor number 3 from which the first read
gets its input. File descriptor 0 is stdin
, 1 is stdout
and 2 is stderr
. You can use other FDs along with them.
I've tested this on Bash and Dash (on my system sh is symlinked to dash).
Of course it works. Here's some more fun:
exec 3<doc1.txt
exec 4<doc2.txt
while read line1 <&3 && read line2 <&4
do
echo "ONE: $line1"
echo "TWO: $line2"
line1=($line1) # convert to an array
line2=($line2)
echo "Colors: ${line1[0]} and ${line2[0]}"
done
This alternates printing the contents of two files, discarding the extra lines of whichever file is longer.
ONE: Red first line of doc1
TWO: Blue first line of doc2
Colors: Red and Blue
ONE: Green second line of doc1
TWO: Yellow second line of doc2
Colors: Green and Yellow
Doc1 only has two lines. The third line and subsequent lines of doc2 are discarded.
这篇关于在 bourne 脚本中重定向 stdin 后获取用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!