在编写BASH程序时,有时候需要解析一大批的参数,这个时候就要我们在程序里面去逐个处理这些参数;而且这些参数的顺序可能是混乱的,本文就介绍几种在BASH中解析这些参数的一些方式。
需求:
- 接收多个命令行选项;
- 每个命令行选项有多种形式;
示例:
./get_options.sh --user root --group=root -f /etc/leidy.conf
- 指定用户名: [-u|–user|–user=] root
- 指定用户组: [-g|–group|–group=] root
- 指定读取的配置文件: [-f|–config|–config=] /etc/leidy.conf
case语句获取参数:
示例代码:
#!/bin/sh # filename: get_options.sh # if [ "$#" -lt 2 ];then echo $"$0: Usage: usage context" exit 1 fi while [ "$1" != "${1##[-+]}" ]; do case $1 in '') echo $"$0: Usage: usage context" exit 2 ;; --user|-u) user=$2 shift 2 ;; --user=?*) user=${1#--user=} shift ;; --group|-g) group=$2 shift 2 ;; --group=?*) group=${1#--group=} shift ;; --config|-f) config=$2 shift 2 ;; --config=?*) config=${1#--config=} shift ;; *) echo $"$0: Usage: usage context" exit 3 ;; esac done
暂无评论