在脚本中使用 getopt
- $ cat extractwithgetopt.sh
- #!/bin/bash
- # Extract command-line options and values with getopt
- #
- set -- $(getopt -q ab:cd "$@")
- #
- echo
- while [ -n "$1" ]
- do
- case "$1" in
- -a) echo "Found the -a option" ;;
- -b) param=$2
- echo "Found the -b option with parameter value $param"
- shift;;
- -c) echo "Found the -c option" ;;
- --) shift
- break;;
- *) echo "$1 is not an option" ;;
- esac
- shift
- done
- #
- echo
- count=1
- for param in $@
- do
- echo "Parameter #$count: $param"
- count=$[ $count + 1 ]
- done
- exit
- $
- $ ./extractwithgetopt.sh -ac
- Found the -a option
- Found the -c option
- $
- $ ./extractwithgetopt.sh -c -d -b BValue -a test1 test2
- Found the -c option
- -d is not an option
- Found the -b option with parameter value 'BValue'
- Found the -a option
- Parameter #1: 'test1'
- Parameter #2: 'test2'
- $
目前看起来相当不错。但是,getopt 命令中仍然隐藏着一个小问题。看看这个例子:
- $ ./extractwithgetopt.sh -c -d -b BValue -a "test1 test2" test3
- Found the -c option
- -d is not an option
- Found the -b option with parameter value 'BValue'
- Found the -a option
- Parameter #1: 'test1
- Parameter #2: test2'
- Parameter #3: 'test3'
- $
getopt 命令并不擅长处理带空格和引号的参数值。它会将空格当作参数分隔符,而不是根
据双引号将二者当作一个参数。好在还有另外的解决方案。