问题描述
我想解析大型脚本的长命令行参数,作为我当前项目的一部分。我之前从未尝试过 getopt 但想第一次尝试使脚本看起来整洁。
在尝试将 getopt 推送到那个大型项目脚本之前,我想先在示例脚本上检查它。
在下面的示例脚本中,解析短命令行参数可以正常工作,但不能解析长命令行参数:
#!/bin/bash
options=$(getopt -o d:f:t: -l domain -l from -l to -- "$@")
[ $? -eq 0 ] || {
echo "Incorrect options provided"
exit 1
}
eval set -- "$options"
while true; do
case "$1" in
-d|--domain)
DOMAIN=$2;
shift
;;
-f|--from)
FROM=$2;
shift
;;
-t|--to)
TO=$2;
shift
;;
--)
shift
break
;;
*)
echo "Invalid options!!";
exit 1
;;
esac
shift
done
echo "Domain is $DOMAIN"
echo "From address is $FROM"
echo "To address is $TO"
exit 0;
输出:
# ./getopt_check.bash -d hello.com -f [email protected] -t [email protected]
Domain is hello.com
From address is [email protected]
To address is [email protected]
# ./getopt_check.bash --domain hello.com -f [email protected] -t [email protected]
Invalid options!!
# ./getopt_check.bash --domain hello.com --from [email protected] --to [email protected]
Invalid options!!
在解析长命令参数时,我也期待相同的输出:
Domain is hello.com
From address is [email protected]
To address is [email protected]
调试时:
# bash -x getopt_check.bash --domain hello.com -f [email protected] -t [email protected]
++ getopt -o d:f:t: -l domain -l from -l to -- --domain hello.com -f [email protected] -t [email protected]
+ options=' --domain -f '\''[email protected]'\'' -t '\''[email protected]'\'' -- '\''hello.com'\'''
+ '[' 0 -eq 0 ']'
+ eval set -- ' --domain -f '\''[email protected]'\'' -t '\''[email protected]'\'' -- '\''hello.com'\'''
++ set -- --domain -f [email protected] -t [email protected] -- hello.com
+ true
+ case "$1" in
+ DOMAIN=-f
+ shift
+ shift
+ true
+ case "$1" in
+ echo 'Invalid options!!'
Invalid options!!
+ exit 1
这里的问题是通过 case switch OR choice -d|--domain
?.
解决方法
我猜是你的 getopt 语法。使用:
getopt -o d:f:t: -l domain:,from:,to: -- "$@"
代替:
getopt -o d:f:t: -l domain -l from -l to -- "$@"