shell脚本中的选项使用

Shell Liemer_Lius 1144℃ 0评论

shell脚本中的选项,可以让用户丰富很多操作:

其中,常用的关键词有:getopts OPTARG OPTIND

getopts:可以获得脚本后面的选项。引号中是定义的选项,可以有多个。

“:d”: 第一个冒号表示如果有错误的时候不提示

“:d:”: 第二个冒号表示-d选项后面必须要有参数,用$OPTARG可以调出这个参数

“:b:d:”: 多个选项也可以,用case来调出这个参数就可以了

while getopts ":b:d:" OPT; do
 case $OPT in
 b)
 echo "The option is b."
 echo "The argument is ${OPTARG}."
 ;;
 d)
 echo "The option is d."
 echo "The argument is ${OPTARG}."
 ;;
 \?)
 echo "Wrong option"
 esac
done
echo $OPTIND 

[root@Master ~]# ./ab.sh -b "option b" -d "option d"
The option is b.
The argument is option b.
The option is d.
The argument is option d.
5

$OPTIND是所有参数的总和,在接下来的脚本中会用到。

这时候,丰富一下以前的shabang脚本:添加Discription信息进脚本

#!/bin/bash
#
# Date: 2018-01-09
# Script Name: shabang.sh
# Author: Liemer_Lius
if [ $# -lt 1 ]; then
echo "One option should be defined."
exit 3
fi
while getopts ":d:" SWITCH; do
case $SWITCH in
d)
DESC=$OPTARG;;
\?)
echo "Usage: ..."
esac
done
shift $[$OPTIND-1]
if ! grep "[^[:space:]]" $1 &>/dev/null; then
cat > $1 << EOF
#!/bin/bash

# Discription: $DESC
# Author: Lius
# Name: `basename $1`
# Version: 0.0.1
# Datetime: `date "+%F %T"`

EOF
fi

vim + $1
until bash -n $1; do
read -p "Syntax error, q|quit for editing: " OPT
case $OPT in
q|quit)
echo "Quit!"
exit 5
;;
*)

vim + $1
;;
esac
done

chmod +x $1

 

转载请注明:liutianfeng.com » shell脚本中的选项使用

喜欢 (0)

发表回复