读取在此文档中被跳过

时间:2013-11-20 08:00:29

标签: linux bash shell

我有一个脚本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"

当我将其作为sh test1.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都能被回显。你能告诉我出了什么问题吗?

2 个答案:

答案 0 :(得分:1)

当您处理here-document时,标准输入是here-document的其余部分。因此,在第一个脚本中,第二个read行正在读取它之后的echo行。由于read正在读取该行,因此它不会被shell执行。

我认为第二个脚本中出错的原因是因为您没有将#!/bin/bash放在脚本的开头。没有它,脚本由sh而不是bash执行,并且它不理解-p的{​​{1}}选项。

在第三个脚本中,read未被回显的原因是因为here读取here文档的shell扩展了here-document中的变量。但是变量$text2是在子shell进程中设置的。您可以使用$text2解决此问题 - 在结束标记周围加上引号意味着here-document应该被视为文字字符串,并且不应该扩展变量。

在最后一个脚本中,重定向来自<<'!'的输入没有做任何事情,因为那是输入已经来自的地方。

答案 1 :(得分:0)

考虑第一个脚本:

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显示为空。

相关问题