shell指令碼專家指南筆記#5_接受命令列選項_開關_引數
##
# 本文為《shell指令碼專家指南》一書的學習筆記。
##
5.接受命令列選項_開關_引數
原文示例有兩部分值得借鑑的內容:
1. app的目錄佈局;
2. getopts的用法。
app的目錄佈局
/usr/local/apphome
/usr/local/apphome/myapp-1.2.3
/usr/local/apphome/myapp-1.2.3/bin
/usr/local/apphome/myapp-1.2.3/log
/usr/local/apphome/myapp-1.2.3/log/myapp.log
/usr/local/apphome/myapp-1.2.3/config
/usr/local/apphome/myapp.sh
#
#>cat $APPHOME/myapp.sh
# MAJOR_VER=1
# MINOR_VER=2
# DOT_VER=3getopts的用法
可以用 man getopts 檢視系統幫助。
OPTIND建議手動初始化為1,雖然shell在啟動時,該變數預設為1,但是為了
在指令碼執行過程中該變數發生更改,建議每次呼叫getopts前初始化該變數。
示例中的ab:c表示接受三個引數,b:表示接受-b引數時,後面必須附加引數值,
-b之後的引數值會賦值給OPTARG變數。如果在ab:c之前增加冒號,如:ab:c,
則為靜默模式,如果接受了錯誤的引數,不會丟擲錯誤"-bash: illegal option"。
示例指令碼: getopts_test.sh----------------------------------------------
#!/bin/bash
OPTIND=1
while getopts ab:c args; do
case $args in
a) echo a ;;
b) echo b $OPTARG;;
c) echo c ;;
esac
done
執行 $ sh getopts_test.sh -a -b bv -c ,顯示如下。
# a
# b bv
# c原文的getopts示例,略作了小修改,增加了DEBUG,修改了部分檔案命名。
使用方法 $ . test.sh; $ jkl; $jkl -l;...
test.sh---------------------------------------------------------------
#!/bin/bash DEBUG=1 APPHOME="/usr/local/apphome" if [ ! -f $APPHOME/myapp.sh ] then echo "Myapp is not installed." exit 1 fi jkl () { USAGE="Usage: \n \ \tjkl [-lbmcdxh] [-f filename] \n \ \t\t[-h] \tThis usage test. \n \ \t\t[-f filename] cat the specified file. \n \ \t\t[-l] \tGo to app log directory with ls. \n \ \t\t[-b] \tGo to app bin directory. \n \ \t\t[-c] \tGo to app config directory. \n \ \t\t[-m] \tGo to app log directory and more log file. \n \ \t\t[-d] \tTurn on debug information. \n \ \t\t[-x] \tTurn off debug information.\n" APPLOG="myapp.log" UNAME="`uname -n`" DATE="`date '+%y%m'`" MYAPP_ID="$APPHOME/myapp.sh" major="`egrep '^MAJOR_VER=' $MYAPP_ID | cut -d '=' -f 2`" minor="`egrep '^MINOR_VER=' $MYAPP_ID | cut -d '=' -f 2`" dot="`egrep '^DOT_VER=' $MYAPP_ID | cut -d '=' -f 2`" APPDIR="$APPHOME/myapp-$major.$minor.$dot" LOGDIR="$APPHOME/myapp-$major.$minor.$dot/log" CFGDIR="$APPHOME/myapp-$major.$minor.$dot/config" BINDIR="$APPHOME/myapp-$major.$minor.$dot/bin" if [ $# -lt 1 ] then echo -e $USAGE fi OPTIND=1 while getopts lf:bmcdxh ARGS; do case $ARGS in l) test $DEBUG -eq 1 && echo "parse arg $ARGS. " if [ -d $LOGDIR ]; then cd $LOGDIR /bin/ls fi ;; f) test $DEBUG -eq 1 && echo "parse arg $ARGS. " FILE=$OPTARG if [ -f $FILE ]; then cat $FILE else echo $FILE not find. Please try again. fi ;; b) test $DEBUG -eq 1 && echo "parse arg $ARGS. " if [ -d $BINDIR ]; then cd $BINDIR fi ;; m) test $DEBUG -eq 1 && echo "parse arg $ARGS. " if [ -d $LOGDIR ]; then cd $LOGDIR /bin/more $APPLOG fi ;; c) test $DEBUG -eq 1 && echo "parse arg $ARGS. " if [ -d $CFGDIR ]; then cd $CFGDIR fi ;; d) test $DEBUG -eq 1 && echo "parse arg $ARGS. " set -x ;; x) test $DEBUG -eq 1 && echo "parse arg $ARGS. " set +x ;; h) test $DEBUG -eq 1 && echo "parse arg $ARGS. " echo -e $USAGE ;; *) test $DEBUG -eq 1 && echo "parse arg $ARGS. " echo -e $USAGE ;; esac done }