Shell腳本是Linux運維工程師必須掌握的一項基本技能。而Shell腳本要想靈活有效地工作,就需要掌握如何獲取命令行輸入的參數個數及參數值。本文將從多個方面詳細闡述Shell參數個數獲取方法。
一、獲取參數個數
Shell腳本可以使用特殊變量”$#”獲取命令行輸入參數的個數。
#/bin/bash echo "The number of argument is $#"
上述代碼運行結果如下:
$ ./test.sh 1 2 3 The number of argument is 3
如果不輸入參數,則結果為0:
$ ./test.sh The number of argument is 0
二、獲取參數值
Shell腳本可以使用特殊變量”$n”獲取第n個命令行輸入參數的值。
#/bin/bash echo "The first argument is $1" echo "The second argument is $2" echo "The third argument is $3"
上述代碼運行結果如下:
$ ./test.sh 1 2 3 The first argument is 1 The second argument is 2 The third argument is 3
如果輸入的參數個數少於對應位置的$n,則會得到空值:
$ ./test.sh 1 2 The first argument is 1 The second argument is 2 The third argument is
三、獲取所有參數
Shell腳本可以使用特殊變量”$@”獲取所有命令行輸入參數:
#/bin/bash echo "All arguments are $@"
上述代碼運行結果如下:
$ ./test.sh 1 2 3 All arguments are 1 2 3
特別地,”$@”在雙引號(“”)中使用時會將每個參數分開,而”$*”會將所有參數看成一個整體:
#/bin/bash echo "All arguments are $*"
上述代碼運行結果如下:
$ ./test.sh 1 2 3 All arguments are 1 2 3
四、結語
Shell參數個數獲取方法是Shell腳本基礎知識之一,掌握此技能不僅可以提高Shell腳本的編寫效率,而且能夠讓Linux運維工程師更好地處理命令行輸入參數。以上是本文對Shell參數獲取方法的多方面闡述,希望能對讀者有所幫助。
原創文章,作者:LERR,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/147821.html