我按照 stackexchange 网站上的帖子来解析命令行参数。我的程序只解析长参数,所有参数都是强制性的。这是我所做的:
getopt --test > /dev/null
if [[ $? -ne 4 ]]; then
echo "getopt --test failed in this environment."
exit 1
fi
function quit {
echo "$1"
exit 1
}
# Option strings
LONG="producer-dir:,consumer-dir:,username:,password:,url:,kafka-host:,checkpoint-dir:"
# read the options
OPTS=$(getopt --longoptions ${LONG} --name "$0" -- "$@")
if [ $? != 0 ]; then
quit "Failed to parse options...exiting."
fi
eval set -- "$OPTS"
# extract options and their arguments into variables.
while true ; do
case "$1" in
--producer-dir )
PRODUCER_DIR="$2"
shift 2
;;
--consumer-dir )
CONSUMER_DIR="$2"
shift 2
;;
--username )
USERNAME="$2"
shift 2
;;
--password )
PASSWORD="$2"
shift 2
;;
--url )
URL="$2"
shift 2
;;
--kafka-host )
KAFKA_HOST="$2"
shift 2
;;
--checkpoint-dir )
CHECKPOINT_DIR="$2"
shift 2
;;
-- )
shift
break
;;
*)
echo "Internal error!"
exit 1
;;
esac
done
无论我以何种顺序传递参数,第一个都被忽略,结果为空。其余参数按预期解析。我错过了什么?