標籤:shell指令碼參數傳遞 shift命令 getopts命令
[本文是自己學習所做筆記,歡迎轉載,但請註明出處:http://blog.csdn.net/jesson20121020]
今天再來看一下如何向shell指令碼傳遞參數,需要掌握兩個命令,一個是 shift命令,另一個是getopts。
指令碼參數傳遞 shift命令
用法:
shift n 每次將參數位置向左位移n位
假如我們要實現統計多個檔案的總行數,就可以用到這個shift命令了,如下:
opt2.sh
#!/bin/bash#op2 static files total lines;staticlines(){ echo "static:`basename $0` filenames" exit}totalline=0if [ $# -lt 2 ]then staticlinesfiwhile [ $# -ne 0 ]do line=`cat $1 | wc -l` echo "$1:${line}" totalline=$[ $totalline+$line ] shiftdoneecho "-------------------------------------"echo "totalline:${totalline}"
給予可執行許可權,執行:
[email protected]:~/develop/worksapce/shell_workspace$ chmod a+rx opt2.sh [email protected]:~/develop/worksapce/shell_workspace$ ./opt2.sh static:opt2.sh filenames[email protected]:~/develop/worksapce/shell_workspace$ ./opt2.sh lsout.txtstatic:opt2.sh filenames[email protected]:~/develop/worksapce/shell_workspace$ ./opt2.sh lsout.txt name.txt lsout.txt:18name.txt:4-------------------------------------totalline:22[email protected]:~/develop/worksapce/shell_workspace$ ./opt2.sh lsout.txt name.txt while_test1.sh lsout.txt:18name.txt:4while_test1.sh:6-------------------------------------totalline:28
通過shift 命令,我們可以很容易地實現統計log等資訊。
getopts命令
該命令可以獲得多個命令列參數。
還是一個指令碼來分析getopts的用法
optsget.sh
#!/bin/bash#optsgetALL=falseHELP=falseFILE=falseVERBOSE=falsewhile getopts ahfvc: OPTIONdo case $OPTION in a) ALL=true echo "ALL is $ALL" ;; h) HELP=true echo "HELP is $HELP" ;; f) FILE=true echo "FILE is $FILE" ;; v) VERBOSE=true echo "VERBOSE is $VERBOSE" ;; c) c=$OPTARG echo "c valuse is $c" ;; \?) echo "`basename $0` -[a h f v] -[c value]" ;; esacdone
給予可執行許可權,執行結果如下:
[email protected]:~/develop/worksapce/shell_workspace$ ./optsget.sh -aALL is true[email protected]:~/develop/worksapce/shell_workspace$ ./optsget.sh -a -fALL is trueFILE is true[email protected]:~/develop/worksapce/shell_workspace$ ./optsget.sh -a -f -hALL is trueFILE is trueHELP is true[email protected]:~/develop/worksapce/shell_workspace$ ./optsget.sh -a -f -h -vALL is trueFILE is trueHELP is trueVERBOSE is true[email protected]:~/develop/worksapce/shell_workspace$ ./optsget.sh -a -f -cALL is trueFILE is true./optsget.sh: 選項需要一個參數 -- coptsget.sh -[a h f v] -[c value][email protected]:~/develop/worksapce/shell_workspace$ ./optsget.sh -a -f -c jessonALL is trueFILE is truec valuse is jesson
不難看出,可以通過getopts命令取得多個參數,而且還可以為每個參數指定值,在需要指定值的參數後加:即可。
linux學習之shell指令碼 ------- 指令碼參數傳遞