Unix bash 错误 - 应为二元运算符

Unix bash error - binary operator expected

下面是我的 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

我现在已经添加了这个

if [ ! -f "$*" ]
then
       echo "Error. File does not exist"
       exit $ERROR_NO_FILE
fi

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

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

...
if [ $# -eq 0 ]
...

您的代码出现错误,因为 $@ 变量扩展为多个单词,这使得 test 命令看起来像这样:

[ -z parm1 parm2 parm3 ... ]

将您的参数用双引号引起来以避免分词和路径名扩展:

for file in "$@"
do
    chmod 755 "$file"
done

if [ -z "$*" ] # Use $* instead of $@ as "$@" expands to multiply words.
then
        echo "Error. No argument."
        exit "$ERROR_CODE_1"
fi

不过您可以稍微更改一下代码:

for file # No need for in "$@" as it's the default
do
    chmod 755 "$file"
done

if [ "$#" -eq 0 ] # $# Contains numbers of arguments passed
then
    >&2 printf 'Error. No argument.\n'
    exit "$ERROR_CODE_1" # What is this?
fi

$@ 扩展到所有参数,它们之间有空格,所以它看起来像:

if [ -z file1 file2 file3 ]

-z 只需要一个词。您需要使用 $* 并引用它,因此它会扩展为一个单词:

if [ -z "$*" ]

这扩展为:

if [ -z "file1 file2 file3" ]

或者只检查参数的数量:

if [ $# -eq 0 ]

您还应该将此检查放在 for 循环之前。你应该在 for 循环中引用参数,这样你就不会遇到带有空格的文件名的问题:

for file in "$@"