Unix bash 错误 - 需要二元运算符

pog*_*123 3 unix bash shell command

下面是我的 bash 脚本中的代码。当我给命令 2 个参数时,我收到一条错误消息,指出二元运算符是预期的(当我给命令 1 个参数时,不会给出错误)。当我给出 2 个参数时,它确实会更改文件权限,因为当我执行 ls -l 时我可以看到它,但它仍然给我这个错误。我如何解决它?

for file in $@
do
    chmod 755 $file
done

if [ -z $@ ]
then
        echo "Error. No argument."
        exit $ERROR_CODE_1
fi
Run Code Online (Sandbox Code Playgroud)

我现在已经添加了这个

if [ ! -f "$*" ]
then
       echo "Error. File does not exist"
       exit $ERROR_NO_FILE
fi
Run Code Online (Sandbox Code Playgroud)

但现在,当我输入超过 1 个参数时,即使文件确实存在,它也会执行 if 语句中的所有操作(即打印 error.file 不存在)。

Jef*_*ler 5

另一种方式:只询问传递了多少个参数:

...
if [ $# -eq 0 ]
...
Run Code Online (Sandbox Code Playgroud)

您在代码中收到错误,因为 $@ 变量扩展为多个单词,这使得命令test如下所示:

[ -z parm1 parm2 parm3 ... ]