简体   繁体   English

构造此简单的if语句时,为什么会出现错误“期望一元运算符”?

[英]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: 有两个参数,它按如下方式进行:

  1. If the first argument is ! 如果第一个参数是! , it just checks if the second argument is empty or not. ,它只是检查第二个参数是否为空。
  2. Otherwise, the first argument must be a unary operator, which foo is not. 否则,第一个参数必须是一元运算符,而foo不是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM