在寫shell腳本時經常會用到命令行選項、參數處理方式,如:
./test.sh -f config.conf -v --prefix=/home
-f 為短選項,它需要一個參數,即config.conf, -v也是一個選項,但它不需要參數
--prefix 是一個長選項,即選項本身多於一個字符,它也需要一個參數,用等號連接,當然等號不是必須的,/home可以直接寫在--prefix後面,即--prefix=/home
在shell中,可以用以下三種方式來處理命令行參數,每種方式都有自己的應用場景
下面我們依次討論這三種處理方式
1. 手工處理方式
在手工處理方式中,首先要知道幾個變量,還是以上面的命令行為例:
$0 : ./test.sh,即命令本身,相當於C/C++中的argv[0]
$1 : -f,第一個參數
$2 : config.conf
$3, $4 ... :類推。
$# : 參數的個數,不包括命令本身,上例中$#為4.
$@ : 參數本身的列表,也不包括命令本身,如上例為 -f config.conf -v --prefix=/home
$* : 和$@相同,但"$*" 和 "$@"(加引號)並不同,"$*"將所有的參數解釋成一個字符串,而"$@"是一個參數數組。如下例所示:
#!/bin/bash
for arg in "$*"
do
echo $arg
done
echo
for arg in "$@"
do
echo $arg
done
$ bash test.sh -f config.conf -v --prefix=/home
-f config.conf -v --prefix=/home #這是"$*"的輸出
-f #以下為$@的輸出
config.conf
-v
--prefix=/home
所以,手工處理的方式即對這些變量的處理。因為手工處理高度依賴於你在命令行上所傳參數的位置,所以一般都只用來處理較簡單的參數。如./test.sh 10。而很少使用./test -n 10這種帶選項的方式。
手工處理方式能滿足大多數的簡單需求,配合shift使用也能構造出強大的功能,但在要處理復雜選項的時候建議用下面的兩種方法。
2. getopts/getopt
處理命令行參數是一個相似而又復雜的事情,在shell中,處理此事的是getopts和getopt
getopts和getopt功能相似但又不完全相同,其中getopt是獨立的可執行文件,而getopts是由bash內置的
先來看看參數傳遞的典型用法:
./test.sh -a -b -c : 短選項,各選項不需參數
./test.sh -abc : 短選項,和上一種方法的效果一樣,只是將所有的選項寫在一起。
./test.sh -a args -b -c :短選項,其中-a需要參數,而-b -c不需參數。
./test.sh --a-long=args --b-long :長選項
我們先來看getopts,它不支持長選項。使用getopts非常簡單:
#!/bin/bash
while getopts "a:bc" arg #選項後面的冒號表示該選項需要參數
do
case $arg in
a)
echo "a's arg:$OPTARG" #參數存在$OPTARG中
;;
b)
echo "b"
;;
c)
echo "c"
;;
?) #當有不認識的選項的時候arg為?
echo "unkonw argument"
exit 1
;;
esac
done
$ bash test.sh -a arg -b -c
a's arg:arg
b
c
$ bash test.sh -a arg -bc
a's arg:arg
b
c
應該說絕大多數腳本使用該函數就可以了,如果需要支持長選項以及可選參數,那麼就需要使用getopt
#!/bin/bash
#-o表示短選項,兩個冒號表示該選項有一個可選參數,可選參數必須緊貼選項
#如-carg 而不能是-c arg
#--long表示長選項
#"$@"在上面解釋過
# -n:出錯時的信息
# -- :舉一個例子比較好理解:
#我們要創建一個名字為 "-f"的目錄你會怎麼辦?
# mkdir -f #不成功,因為-f會被mkdir當作選項來解析,這時就可以使用
# mkdir -- -f 這樣-f就不會被作為選項。
TEMP=`getopt -o ab:c:: --long a-long,b-long:,c-long:: \
-n 'example.bash' -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
# Note the quotes around `$TEMP': they are essential!
#set 會重新排列參數的順序,也就是改變$1,$2...$n的值,這些值在getopt中重新排列過了
eval set -- "$TEMP"
#經過getopt的處理,下面處理具體選項。
while true ; do
case "$1" in
-a|--a-long) echo "Option a" ; shift ;;
-b|--b-long) echo "Option b, argument \`$2'" ; shift 2 ;;
-c|--c-long)
# c has an optional argument. As we are in quoted mode,
# an empty parameter will be generated if its optional
# argument is not found.
case "$2" in
"") echo "Option c, no argument"; shift 2 ;;
*) echo "Option c, argument \`$2'" ; shift 2 ;;
esac ;;
--) shift ; break ;;
*) echo "Internal error!" ; exit 1 ;;
esac
done
echo "Remaining arguments:"
for arg do
echo '--> '"\`$arg'" ;
done
$ bash test.sh -a -b arg arg1 -c
Option a
Option b, argument `arg'
Option c, no argument
Remaining arguments:
--> `arg1'
可以看到,命令行中多了個arg1參數,在經過getopt和set之後,命令行會變為:
-a -b arg -c -- arg1
$1指向-a,$2指向-b,$3指向arg,$4指向-c,$5指向--,而多出的arg1則被放到了最後
3. 舉例
如將前面的ssh.exp、scp.exp封裝起來,代碼:
#!/bin/bash
###################### proc defination ########################
# ignore rule
ignore_init()
{
# ignore password
array_ignore_pwd_length=0
if [ -f ./ignore_pwd ]; then
while read IGNORE_PWD
do
array_ignore_pwd[$array_ignore_pwd_length]=$IGNORE_PWD
let array_ignore_pwd_length=$array_ignore_pwd_length+1
done < ./ignore_pwd
fi
# ignore ip address
array_ignore_ip_length=0
if [ -f ./ignore_ip ]; then
while read IGNORE_IP
do
array_ignore_ip[$array_ignore_ip_length]=$IGNORE_IP
let array_ignore_ip_length=$array_ignore_ip_length+1
done < ./ignore_ip
fi
}
show_version()
{
echo "version: 1.0"
echo "updated date: 2014-01-09"
}
show_usage()
{
echo -e "`printf %-16s "Usage: $0"` [-h|--help]"
echo -e "`printf %-16s ` [-v|-V|--version]"
echo -e "`printf %-16s ` [-l|--iplist ... ]"
echo -e "`printf %-16s ` [-c|--config ... ]"
echo -e "`printf %-16s ` [-t|--sshtimeout ... ]"
echo -e "`printf %-16s ` [-T|--fttimeout ... ]"
echo -e "`printf %-16s ` [-L|--bwlimit ... ]"
echo -e "`printf %-16s ` [-n|--ignore]"
#echo "ignr_flag: 'ignr'-some ip will be ignored; otherwise-all ip will be handled"
}
# Default Parameters
myIFS=":::" # 配置文件中的分隔符
TOOLDIR=/root/scripts
cd $TOOLDIR
IPLIST="iplist.txt" # IP列表,格式為IP 端口 用戶名 密碼
CONFIG_FILE="config.txt" # 命令列表和文件傳送配置列表,關鍵字為com:::和file:::
IGNRFLAG="noignr" # 如果置為ignr,則腳本會進行忽略條件的判斷
SSHTIMEOUT=100 # 遠程命令執行相關操作的超時設定,單位為秒
SCPTIMEOUT=2000 # 文件傳送相關操作的超時設定,單位為秒
BWLIMIT=1024000 # 文件傳送的帶寬限速,單位為kbit/s
# 入口參數分析
TEMP=`getopt -o hvVl:c:t:T:L:n --long help,version,iplist:,config:,sshtimeout:,fttimeout:,bwlimit:,ignore -- "$@" 2>/dev/null`
[ $? != 0 ] && echo -e "\033[31mERROR: unknown argument! \033[0m\n" && show_usage && exit 1
# 會將符合getopt參數規則的參數擺在前面,其他擺在後面,並在最後面添加--
eval set -- "$TEMP"
while :
do
[ -z "$1" ] && break;
case "$1" in
-h|--help)
show_usage; exit 0
;;
-v|-V|--version)
show_version; exit 0
;;
-l|--iplist)
IPLIST=$2; shift 2
;;
-c|--config)
CONFIG_FILE=$2; shift 2
;;
-t|--sshtimeout)
SSHTIMEOUT=$2; shift 2
;;
-T|--fttimeout)
SCPTIMEOUT=$2; shift 2
;;
-L|--bwlimit)
BWLIMIT=$2; shift 2
;;
-n|--ignore)
IGNRFLAG="ignr"; shift
;;
--)
shift
;;
*)
echo -e "\033[31mERROR: unknown argument! \033[0m\n" && show_usage && exit 1
;;
esac
done
################ main #######################
BEGINDATETIME=`date "+%F %T"`
[ ! -f $IPLIST ] && echo -e "\033[31mERROR: iplist \"$IPLIST\" not exists, please check! \033[0m\n" && exit 1
[ ! -f $CONFIG_FILE ] && echo -e "\033[31mERROR: config \"$CONFIG_FILE\" not exists, please check! \033[0m\n" && exit 1
echo
echo "You are using:"
echo -e "`printf %-16s "\"$CONFIG_FILE\""` ---- as your config"
echo -e "`printf %-16s "\"$IPLIST\""` ---- as your iplist"
echo -e "`printf %-16s "\"$SSHTIMEOUT\""` ---- as your ssh timeout"
echo -e "`printf %-16s "\"$SCPTIMEOUT\""` ---- as your scp timeout"
echo -e "`printf %-16s "\"$BWLIMIT\""` ---- as your bwlimit"
echo -e "`printf %-16s "\"$IGNRFLAG\""` ---- as your ignore flag"
echo
[ -f ipnologin.txt ] && rm -f ipnologin.txt
IPSEQ=0
while read IP PORT USER PASSWD PASSWD_2ND PASSWD_3RD PASSWD_4TH OTHERS
do
[ -z "`echo $IP | grep -E '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'`" ] && continue
[ "`python $TOOLDIR/ckssh.py $IP $PORT`" == 'no' ] && echo "$IP" >> ipnologin.txt && continue
let IPSEQ=$IPSEQ+1
# 如果啟用了忽略,則進入忽略流程
if [ $IGNRFLAG == "ignr" ]; then
ignore_init
ignored_flag=0
i=0
while [ $i -lt $array_ignore_pwd_length ]
do
[ ${PASSWD}x == ${array_ignore_pwd[$i]}x ] && ignored_flag=1 && break
let i=$i+1
done
[ $ignored_flag -eq 1 ] && continue
j=0
while [ $j -lt $array_ignore_ip_length ]
do
[ ${IP}x == ${array_ignore_ip[$j]}x ] && ignored_flag=1 && break
let j=$j+1
done
[ $ignored_flag -eq 1 ] && continue
fi
####### Try password from here ####
for PW in $PASSWD $PASSWD_2ND $PASSWD_3RD $PASSWD_4TH
do
PASSWD_USE=$PW
$TOOLDIR/ssh.exp $IP $USER $PW $PORT true $SSHTIMEOUT
[ $? -eq 0 ] && PASSWD_USE=$PW && break
done
# 針對一個$IP,執行配置文件中的一整套操作
while read eachline
do
# 必須以com或file開頭
[ -z "`echo $eachline | grep -E '^com|^file'`" ] && continue
myKEYWORD=`echo $eachline | awk -F"$myIFS" '{ print $1 }'`
myCONFIGLINE=`echo $eachline | awk -F"$myIFS" '{ print $2 }'`
# 對配置文件中的預定義的可擴展特殊字符串進行擴展
# 關鍵字#IP#,用$IP進行替換
if [ ! -z "`echo "$myCONFIGLINE" | grep '#IP#'`" ]; then
myCONFIGLINE_temp=`echo $myCONFIGLINE | sed "s/#IP#/$IP/g"`
myCONFIGLINE=$myCONFIGLINE_temp
fi
# 時間相關關鍵字,用當前時間進行替換
if [ ! -z "`echo "$myCONFIGLINE" | grep '#YYYY#'`" ]; then
myYEAR=`date +%Y`
myCONFIGLINE_temp=`echo $myCONFIGLINE | sed "s/#YYYY#/$myYEAR/g"`
myCONFIGLINE=$myCONFIGLINE_temp
fi
if [ ! -z "`echo "$myCONFIGLINE" | grep '#MM#'`" ]; then
myMONTH=`date +%m`
myCONFIGLINE_temp=`echo $myCONFIGLINE | sed "s/#MM#/$myMONTH/g"`
myCONFIGLINE=$myCONFIGLINE_temp
fi
if [ ! -z "`echo "$myCONFIGLINE" | grep '#DD#'`" ]; then
myDATE=`date +%d`
myCONFIGLINE_temp=`echo $myCONFIGLINE | sed "s/#DD#/$myDATE/g"`
myCONFIGLINE=$myCONFIGLINE_temp
fi
if [ ! -z "`echo "$myCONFIGLINE" | grep '#hh#'`" ]; then
myHOUR=`date +%H`
myCONFIGLINE_temp=`echo $myCONFIGLINE | sed "s/#hh#/$myHOUR/g"`
myCONFIGLINE=$myCONFIGLINE_temp
fi
if [ ! -z "`echo "$myCONFIGLINE" | grep '#mm#'`" ]; then
myMINUTE=`date +%M`
myCONFIGLINE_temp=`echo $myCONFIGLINE | sed "s/#mm#/$myMINUTE/g"`
myCONFIGLINE=$myCONFIGLINE_temp
fi
if [ ! -z "`echo "$myCONFIGLINE" | grep '#ss#'`" ]; then
mySECOND=`date +%S`
myCONFIGLINE_temp=`echo $myCONFIGLINE | sed "s/#ss#/$mySECOND/g"`
myCONFIGLINE=$myCONFIGLINE_temp
fi
# IPSEQ關鍵字,用當前IP的序列號替換,從1開始
if [ ! -z "`echo "$myCONFIGLINE" | grep '#IPSEQ#'`" ]; then
myCONFIGLINE_temp=`echo $myCONFIGLINE | sed "s/#IPSEQ#/$IPSEQ/g"`
myCONFIGLINE=$myCONFIGLINE_temp
fi
# 配置文件中有關鍵字file:::,就調用scp.exp進行文件傳送
if [ "$myKEYWORD"x == "file"x ]; then
SOURCEFILE=`echo $myCONFIGLINE | awk '{ print $1 }'`
DESTDIR=`echo $myCONFIGLINE | awk '{ print $2 }'`
DIRECTION=`echo $myCONFIGLINE | awk '{ print $3 }'`
$TOOLDIR/scp.exp $IP $USER $PASSWD_USE $PORT $SOURCEFILE $DESTDIR $DIRECTION $BWLIMIT $SCPTIMEOUT
[ $? -ne 0 ] && echo -e "\033[31mSCP Try Out All Password Failed\033[0m\n"
# 配置文件中有關鍵字com:::,就調用ssh.exp進行遠程命令執行
elif [ "$myKEYWORD"x == "com"x ]; then
$TOOLDIR/ssh.exp $IP $USER $PASSWD_USE $PORT "${myCONFIGLINE}" $SSHTIMEOUT
[ $? -ne 0 ] && echo -e "\033[31mSSH Try Out All Password Failed\033[0m\n"
else
echo "ERROR: configuration wrong! [$eachline] "
echo " where KEYWORD should not be [$myKEYWORD], but 'com' or 'file'"
echo " if you dont want to run it, you can comment it with '#'"
echo ""
exit
fi
done < $CONFIG_FILE
done < $IPLIST
ENDDATETIME=`date "+%F %T"`
echo "$BEGINDATETIME -- $ENDDATETIME"
echo "$0 $* --excutes over!"
exit 0
原文:http://blog.linuxeye.com/389.html