Shell getopt第一个参数错误

Shell getopt first parameter error

运行下面的代码,我发现host_ip是空的,不知道是什么原因?

TEMP=`getopt --long hostip:,hostport: -n 'javawrap' -- "$@"`

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

eval set -- "$TEMP"

host_ip=
host_port=

while true; do
  case "" in
    --hostip ) host_ip=""; shift 2;;
    --hostport ) host_port=""; shift 2 ;;
    * ) break ;;
  esac
done

echo $host_ip
echo $host_port

看来您需要为 getopt 指定短选项,否则它 (IMO) 会搞乱解析。来自 man getopt:

If this option is not found, the first parameter of getopt that does not start with a '-' (and is not an option argument) is used as the short options string.

这个有效:

$ getopt --options '' --longoptions hostip:,hostport: -n 'javawrap' -- --hostip foo --hostport bar
 --hostip 'foo' --hostport 'bar' --