shell 特殊的位置引數變數
阿新 • • 發佈:2021-01-14
技術標籤:linux
$1 $2 $3 ... ${10} ${11} $0 $# $* [email protected] ################ $1 $2 $3 ... ${10} ${11} 實踐 ####################### $ cat hello.sh echo $1 $2 (( sum=$1+$2 )) echo $sum $ bash hello.sh 2 5 2 5 7 ############### $0 dirname basename 實踐 ################################# $ cat /home/dc2-user/dir/child/hello.sh echo $0 $ cd /home/dc2-user/dir/child && bash hello.sh hello.sh $ cd /home $ bash ./dc2-user/dir/child/hello.sh ./dc2-user/dir/child/hello.sh $ bash dc2-user/dir/child/hello.sh dc2-user/dir/child/hello.sh 通過上面的例子我們可以看到 $0 是列印當前執行指令碼的全路徑,輸出的結果與我們如何表示檔案路徑的方式有關(絕對路徑 相對路徑 等) 如果我們想要單獨拿到執行的目錄或者檔名的部分,就需要用到 dirname 和 basename $ dirname /home/dc2-user/dir/child/hello.sh /home/dc2-user/dir/child $ basename /home/dc2-user/dir/child/hello.sh hello.sh $ cd /home && basename dc2-user/dir/child/hello.sh hello.sh $ cd /home && dirname dc2-user/dir/child/hello.sh dc2-user/dir/child ############################# $# 位置引數實踐 ################################### $ cat q.sh echo $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} echo $# $ bash q.sh {1..20} 1 2 3 4 5 6 7 8 9 10 11 20 可以看到 $# 是用來確定實際傳入指令碼的引數個數,比如某些時候我們寫的指令碼要求必須傳入2個引數,不能多不能少,我們就可以利用這個 $# 來實現,如下 $ cat q2.sh if [ $# -ne 2 ]; then echo "USAGE: /bin/bash $0 arg1 arg2" echo "引數必須是兩個" exit fi echo "bula bula bula" $ bash q2.sh USAGE: /bin/bash q2.sh arg1 arg2 引數必須是兩個 $ bash ~/q2.sh USAGE: /bin/bash /home/dc2-user/q2.sh arg1 arg2 引數必須是兩個