簡體   English   中英

確認shell函數的有效輸入參數數量

[英]Confirming the number of valid input arguments of a shell function

假設一個外殼函數my_function期望接收三個有效的輸入參數:

my_function()
{
   echo "Three common metasyntactic variables are: $1 $2 $3"
}

我想在my_function中包含一個測試,以評估該函數是否確實已接收到三個輸入參數, 並且這些輸入參數都不為空。

$ my_function foo bar baz
Three common metasyntactic variables are: foo bar baz

$ my_function foo bar  # By default, no error message is given, which I wish to avoid
Three common metasyntactic variables are: foo bar

我將如何實施?

編輯1 :如上所述,我正在尋找的代碼不僅要確認輸入變量的數量,還要確認它們都不為空。 第二個方面很重要,因為輸入變量可能是從其他函數傳遞來的變量本身。

bash變量$#包含傳遞給腳本函數的命令行參數的長度。

my_function() {
    (( "$#" == 3 )) || { printf "Lesser than 3 arguments received\n"; exit 1; }
}

同樣,如果您想以僅包含空格的方式檢查任何自變量是否為 ,則可以遍歷自變量並對其進行檢查。

for (( i=1; i<="$#"; i++ )); do
    argVal="${!i}"
    [[ -z "${argVal// }" ]] && { printf "Argument #$i is empty\n"; exit 2; }
done

如果您以較少的參數調用函數,則將兩者結合

my_function "foo" "bar"
Lesser than 3 arguments received

對於空參數,

my_function "foo" "bar" " "
Argument #3 is empty

您可以辯稱這些變量是用${var:?}

my_function()
{
   echo "Three common metasyntactic variables are: ${1:?} ${2:?} ${3:?}"
}

當值為空或未設置時,這將失敗:

$ my_function foo bar baz
Three common metasyntactic variables are: foo bar baz

$ my_function foo bar
bash: 3: parameter null or not set

$ my_function foo "" baz
bash: 2: parameter null or not set

同樣,您可以使用${1?}來允許空字符串,但是對於未設置的變量仍然會失敗。

暫無
暫無

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

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