平常在写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

本文介绍了如何在Shell脚本中通过参数名传递参数值,以提高可读性和维护性。通常使用$1,$2等变量接收参数,但这种方式存在弊端。为了与Linux命令类似,我们可以利用getopt实现短参数名和长参数名的参数值获取,使得脚本更加易用和规范。"
111609371,10294744,R语言数据结构详解:向量、矩阵、数据框与因子,"['R语言', '数据类型', '数据结构', '矩阵操作', '因子处理']
5991

被折叠的 条评论
为什么被折叠?



