簡體   English   中英

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

但是現在當我輸入多個參數時,即使文件確實存在,它也會在if語句中執行所有操作(即,打印error.file不存在)。

用另一種方式做:只問傳遞了多少個參數:

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

因為$ @變量擴展為多個單詞,所以在代碼中出現錯誤,這使test命令看起來像這樣:

[-z parm1 parm2 parm3 ...]

$@擴展到所有參數,它們之間有空格,因此看起來像:

if [ -z file1 file2 file3 ]

但是-z后面只需要一個字。 您需要使用$*並將其引號,因此它將擴展為一個單詞:

if [ -z "$*" ]

擴展為:

if [ -z "file1 file2 file3" ]

或者只是檢查參數數量:

if [ $# -eq 0 ]

您還應該將此檢查放在for循環之前。 並且您應該在for循環中引用該參數,這樣,帶空格的文件名就不會出現問題:

for file in "$@"

將參數用雙引號引起來,以避免單詞拆分和路徑名擴展:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM