[英]Why do I get the error “Unary Operator Expected” when constructing this simple if else statement?
I'm making a program, lab5, to test if the argument is a directory or a file. 我正在编写一个程序lab5来测试参数是目录还是文件。 when I run the program with "bash lab5", I get "unary operator expected on line 3 and 5" What is the problem?
当我使用“ bash lab5”运行程序时,出现“第3行和第5行上的一元运算符”是什么问题? Thanks!
谢谢!
#!/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"
fi 科幻
test
does not have postfix operators, only prefix and infix operators. test
没有后缀运算符,只有前缀和中缀运算符。 -f
and -d
are both prefix operators, meaning they come before the argument you want to 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
The exact error occurs because the shell sees something like test foo -d
, and notes that test
received exactly two arguments. 发生确切的错误是因为外壳程序看到诸如
test foo -d
,并指出test
恰好接收了两个参数。 With two arguments, it proceeds as follows: 有两个参数,它按如下方式进行:
!
!
, it just checks if the second argument is empty or not. foo
is not. foo
不是。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.