对于最终项目,我正在尝试创建一个 shell 脚本,以方便用户创建。要求包括我从文件中读取信息并据此创建用户。这是我遇到问题的代码片段。
echo -n "Please provide a path to the file containing these parameters: "
read inputPath
fileInfo = $(grep $inputPath)
if [ -n "$fileInfo" ]; then
IFS="," read firstName lastName phoneNo emailAd < "$fileInfo"
else
echo "Cannot read, file is empty." >&2
exit 1
fi
读取 inputPath 后,它不会停止接受输入并继续执行下一行代码。我完全被难住了。
感谢您的浏览。
最佳答案
这根本不能用作赋值语句:
fileInfo = $(grep $inputPath)
shell 不允许在赋值中的 =
周围有空格。即使我们解决了这个问题,我们仍然会遇到另一个问题:
fileInfo=$(grep $inputPath)
如果 inputPath
是一个没有空格的路径,那么 grep
将在 stdin 中查找该字符串,并且它将继续查找,直到您按 ctrl-D 关闭标准输入。
您可以通过在命令提示符下尝试来演示这一点:
$ inputPath=/usr/bin/python
$ grep $inputPath
shell 将等待您提供输入。
您很可能想在名为 $inputPath
的文件中搜索某些内容:
fileInfo=$(grep something "$inputPath")
请注意,我们引用了 inputPath
以防止分词和路径名扩展。
有关带空格的命令的更多信息
让我们再看一遍:
fileInfo = $(grep $inputPath)
如果 shell 看到此命令,它将尝试使用第一个参数 =
运行命令 fileInfo
,其余参数是分词和路径名扩展的结果无论 $(grep $inputPath)
产生什么。但是,要做到这一点,正如 Jonathan Leffler 在评论中指出的那样,shell 必须首先运行 grep $inputPath
。只要 $inputPath
不包含空格,grep
就会读取标准输入,查找与 $inputPath
值匹配的文本。除非输入 ctrl-D,否则 shell 会卡在此处。
换句话说,即使带有额外空格的命令版本存在多个问题,第一个要注意的问题是 grep
正在等待 stdin .
关于bash - 无法停止读取 Shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38627900/