##
# 本文为《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
}