我有一个脚本test1.sh。它对所有用户都具有rwx权限。它载有以下案文:
echo "You are in test1.sh"
read -p "Enter some text : " text1
echo "You entered : $text1"
bash <<!
echo "You are now in a here-document"
read -p "Enter some more text : " text2
echo "You also entered : $text2"
echo "End of the here-document"
!
echo "End of test1.sh"当我以shtest1.sh的形式运行它时,第二个read语句将被完全跳过。这是输出:
$ sh test1.sh
You are in test1.sh
Enter some text : hello
You entered : hello
You are now in a here-document
End of the here-document
End of test1.sh当我以./test1.sh的形式运行它时,两个语句都会被跳过。
$ ./test1.sh
You are in test1.sh
./test1.sh[11]: read: no query process
You entered :
You are now in a here-document
End of the here-document
End of test1.sh如果我将test1.sh更改为使用/dev/tty,
echo "You are in test1.sh"
read -p "Enter some text : " text1
echo "You entered : $text1"
bash <<!
echo "You are now in a here-document" > /dev/tty
read -p "Enter some more text : " text2 < /dev/tty
echo "You also entered : $text2" > /dev/tty
echo "End of the here-document" > /dev/tty
!
echo "End of test1.sh"然后我得到:
$ sh test1.sh
You are in test1.sh
Enter some text : hello
You entered : hello
You are now in a here-document
Enter some more text : bye
You also entered :
End of the here-document
End of test1.sh第二个文本没有被打印出来。
如果我编辑文件使用stdin和stdout,
echo "You are in test1.sh"
read -p "Enter some text : " text1
echo "You entered : $text1"
bash <<!
echo "You are now in a here-document" > /dev/stdout
read -p "Enter some more text : " text2 < /dev/stdin
echo "You also entered : $text2" > /dev/stdout
echo "End of the here-document" > /dev/stdout
!
echo "End of test1.sh",我得到这个输出:
$ sh test1.sh
You are in test1.sh
Enter some text : hello
You entered : hello
You are now in a here-document
You also entered :
End of the here-document
End of test1.sh我无法为第二条读语句输入任何文本
我希望将每个read语句中的输入分别读入text1和text2,并且希望$text1和$text2都被回显。你能告诉我怎么回事吗?
发布于 2013-11-20 08:10:55
在处理这里文档时,标准输入是这里文档的其余部分。因此,在第一个脚本中,第二个read行读取后面的echo行。因为该行是由read读取的,所以它不会由shell执行。
我认为第二个脚本中出现错误的原因是没有将#!/bin/bash放在脚本的开头。否则,脚本将由sh而不是bash执行,并且它不理解read的-p选项。
在第三个脚本中,$text2没有得到响应的原因是,这里文档中的变量是由读取这里文档的shell展开的。但是变量$text2是在子shell进程中设置的。你可以用<<'!'来解决这个问题--把引号放在结束标记上,这意味着这里的文档应该被看作是一个文字字符串,而变量不应该被展开。
在最后一个脚本中,从/dev/stdin重定向输入不起任何作用,因为这就是输入的来源。
发布于 2013-11-20 08:06:20
考虑第一个脚本:
echo "You are in test1.sh"
read -p "Enter some text : " text1
echo "You entered : $text1"
bash <<!
echo "You are now in a here-document"
read -p "Enter some more text : " text2
echo "You also entered : $text2"
echo "End of the here-document"
!
echo "End of test1.sh"bash的标准输入来自哪里?答:这里的文件。因此,read也尝试从标准输入中读取。很有可能,shell已经读取了所有内容,所以read变成了空的。
https://stackoverflow.com/questions/20090374
复制相似问题