getopt vs getopts

getopt示例
#!/bin/bash
aflag=no
args=`getopt a: $@`

if [ $? -ne 0 ]; then
    echo 'Usage: ...'
    exit 2
fi

set -- $args

while [ $# -gt 0 ]
do
    case "$1" in
    (-a) echo "-a was triggered, Parameter: $OPTARG" >&2;;
    (--) shift; non_option_arguments=$@; break;;
    (-*) echo "$0: error - unrecognized option $1" 1>&2; exit 1;;
    (*)  break;;
    esac
    shift
done
getopts示例
#!/bin/bash
 
while getopts ":a:" opt; do
  case $opt in
    a)
      echo "-a was triggered, Parameter: $OPTARG" >&2
      ;;
    ?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

shift $((OPTIND-1))
non_option_arguments=$@
getopt 是单独的一个程序,getopts 是 bash 内建命令;getopts 不支持长参数(--起头的参数),而 getopt 支持。
对比之下,getopt 似乎有着更广的应用范围。
 
但是,却有着致命的缺陷。请看下面,当调用 getopt 命令后,输入被重新整理,如下
#getopt 'a:bcdfe' -a 90 -c lllllllll
-a 90 -c -- lllllllll
但当调用 set 将整理后的输出重新设置为程序参数时,问题出现了。如果你的参数包含 空格 或 glob,如
"a   b" 
"/bin/*"

含空格的参数会被识别为多个参数;含glob的参数会被展开。

结论:getopt 只适合于解析参数不含空格或glob的情况。

原文地址:https://www.cnblogs.com/JesseFang/p/3343104.html