許多人寫shell或其他程式喜歡用$0/$1/$2...來取得輸入變數,不過卻有可能造成擴充性與閱讀性的問題。建議使用 getops 來取代 $0/$1來減少擴充與閱讀性的困難。
【目的】
- getopts 的使用
- shift 的使用
- 如何在shell 裡面作算數運算
#!/bin/bash
aflag=
bflag=
while getopts ab: name
do
case $name in
a) aflag=1;;
b) bflag=1
bval="$OPTARG";;
*) printf "Usage: %s: [-a] [-b value] args\n" $0
exit 2;;
esac
done
if [ ! -z "$aflag" ]; then
printf "Option -a specified\n"
fi
if [ ! -z "$bflag" ]; then
printf 'Option -b "%s" specified\n' "$bval"
fi
shift $(($OPTIND - 1))
printf "Remaining arguments are: %s\n" "$*"
【結果】
$ ./opt.sh -a -b 123 attachment Option -a specified Option -b "123" specified Remaining arguments are: attachment $./opt.sh -a -b 123 -c attachment ./opt.sh: illegal option -- c Usage: ./opt.sh: [-a] [-b value] args
【參考】
- The Single UNIX ® Specification, Version 2 (本文所參考的script)
http://www.opengroup.org/onlinepubs/7990989799/xcu/getopts.html - Shell脚本语法(請參考 case 用法)
http://learn.akae.cn/media/ch31s05.html - strlen的判斷(文章下面)
http://opensource.tpc.edu.tw/download/pub/shell/c954.html - Small getopts tutorial
http://bash-hackers.org/wiki/doku.php/howto/getopts_tutorial - getopts
http://www.softpanorama.org/Utilities/getopts.shtml
【問題】
- getopt 和 getopts 有何不同?

