平常在写shell脚本都是用$1,$2…这种方式来接收参数,然而这种接收参数的方式不但容易忘记且不易于理解和维护。而且在调用该shell脚本传递参数时容易产出错误。
Linux常用的命令都可指定参数名和参数值,我们怎样才能给自己的shell脚本也采用参数名和参数值这样的方式来获取参数值呢?下面的例子定义了短参数名和长参数名两种获取参数值的方式。其实是根据getopt提供的特性进行整理而来。
#!/bin/sh
#样例一
show_usage="args: [-l , -r , -b , -w]\
[--local-repository=, --repository-url=, --backup-dir=, --webdir=]"
#参数
# 本地仓库目录
opt_localrepo=""
# git仓库url
opt_url=""
# 备份目录
opt_backupdir=""
# web目录
opt_webdir=""
GETOPT_ARGS=`getopt -o l:r:b:w: -al local-repository:,repository-url:,backup-dir:,webdir: -- "$@"`
eval set -- "$GETOPT_ARGS"
#获取参数
while [ -n "$1" ]
do
case "$1" in
-l|--local-repository) opt_localrepo=$2; shift 2;;
-r|--repository-url) opt_url=$2; shift 2;;
-b|--backup-dir) opt_backupdir=$2; shift 2;;
-w|--webdir) opt_webdir=$2; shift 2;;
--) break ;;
*) echo $1,$2,$show_usage; break ;;
esac
done
if [[ -z $opt_localrepo || -z $opt_url || -z $opt_backupdir || -z $opt_webdir ]]; then
echo $show_usage
echo "opt_localrepo: $opt_localrepo , opt_url: $opt_url , opt_backupdir: $opt_backupdir , opt_webdir: $opt_webdir"
exit 0
fi
#用法:
sh **.sh -l value1 -r value2 -b value3 ...
sh **.sh --local-repository=value1 --repository-url==value2 ...
#样例二
ARGS=`getopt -a -o u:t:s:c:p:m: -l username:,taskid:,stage:city:,project:model: -- "$@"`
eval set -- "${ARGS}"
echo "parse start"
while true
do
case "$1" in
-u|--username)
username="$2"
shift
;;
-t|--taskid)
taskid="$2"
shift
;;
-s|--stage)
stage="$2"
shift
;;
-c|--city)
city="$2"
shift
;;
-p|--project)
project="$2"
shift
;;
-m|--model)
model="$2"
shift
;;
--)
shift
break
;;
esac
shift
done
# if not exist city/project/model
if [ -z $city ];then
city="null"
fi
if [ -z $project ];then
project="null"
fi
if [ -z $model ];then
model="normal"
fi