我正在编写一个程序 lab5,以测试参数是目录还是文件。当我用“bash lab5”运行程序时,我得到“第 3 行和第 5 行预期的一元运算符”这是什么问题?谢谢!
#!/bin/bash
if test "$1" -d
then
echo "This is a directory"
elif test "$1" -f
then
echo "This is a file"
else
echo "This is neither a file or a directory"
我
最佳答案
test
没有后缀运算符,只有前缀和中缀运算符。 -f
和 -d
都是前缀运算符,这意味着它们出现在您要测试的参数之前。
if test -d "$1"
then
echo "This is a directory"
elif test -f "$1"
then
echo "This is a file"
else
echo "This is neither a file or a directory"
fi
确切的错误发生是因为 shell 看到类似 test foo -d
的内容,并注意到 test
正好收到两个参数。有两个参数,它按如下方式进行:
- 如果第一个参数是
!
,它只检查第二个参数是否为空。 - 否则,第一个参数必须是一元运算符,而
foo
不是。
关于linux - 为什么在构建这个简单的 if else 语句时会出现错误 "Unary Operator Expected"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42562137/