Skip to content

Instantly share code, notes, and snippets.

@gotnix
Last active January 11, 2024 12:34
Show Gist options
  • Select an option

  • Save gotnix/4367156 to your computer and use it in GitHub Desktop.

Select an option

Save gotnix/4367156 to your computer and use it in GitHub Desktop.
使用Bash内置的getopts 处理脚本的命令行参数。
#!/bin/bash
# 该脚本转自http://www.bsdmap.com/2011/06/28/bash-getopts/, 稍作修改
# http://stackoverflow.com/a/7530327/1699746 使用 CLI 传参数的选项到一个数组。
# 更多参考:
# Small getopts tutorial - http://wiki.bash-hackers.org/howto/getopts_tutorial
# Bash Shell中命令行选项/参数处理 - http://www.cnblogs.com/FrankTan/archive/2010/03/01/1634516.html
# Bash里使用getopts解析非选项参数 - \
# http://blog.yegle.net/2011/04/21/parsing-non-option-argument-bash-getopts/
# 使用getopt传递脚本选项参数 - http://www.linuxfly.org/post/168/
#
# 须向之前有 `:' 是静默执行 `getopts',需要自行处理报错,选项后跟一个冒号,表示必须有参数,2 个冒号是选项有可选参数。
usage() {
cat << -EOF-
Usage:
$0 -I interface -i ipaddr
-EOF-
exit 1
}
while getopts “I:i:” opt ; do
case $opt in
I)
interface=$OPTARG
;;
i)
ip=$OPTARG
;;
?) usage
;;
esac
done
if [[ -z "$interface" || -z "$ip" ]] ; then
usage
else
ifconfig $interface | grep -iE "${ip}\b"
fi
#下面的脚本是Emacs 的Shell-script 模式Optinos loop[C-c C-o] 生成的:
while getopts :"o:t:" OPT; do
case $OPT in
"|+")
;;
o|+o)
"$OPTARG"
;;
t|+t)
"$OPTARG"
;;
"|+")
;;
*)
echo "usage: `basename $0` [+-"o ARG] [+-t ARG] [+-"} [--] ARGS..."
exit 2
esac
done
shift `expr $OPTIND - 1`
OPTIND=1
# Optinos loop[C-c C-o] 生成的脚本结束
# shift $(( $OPTIND-1 )) 作用就是把具有 `-' 的,给 getopts 处理的命令行位置参数都 unset 了,
# 使用场景类似 `ls -l -h /tmp' 这样的命令,把 -l、-h 选项都给 unset 了,让最后的 `/tmp' 成为 ${1} 的值。
# Bash 支持间接引用的版本直接用 `${!OPTIND}' 的值就是 `/tmp' ,放在 case 语句之外就可以;
# 还没想明白放在 `while' 循环体里结果也是对的,`getops' 在没有选项的时候不知道返回值是什么,要测试一下。
exit $?
@J2M3L2

J2M3L2 commented Apr 5, 2017

Copy link
Copy Markdown

line 68 : 错别字 while

@gotnix

gotnix commented Jan 11, 2024

Copy link
Copy Markdown
Author

line 68 : 错别字 while

感谢评论,已修改。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment