我正在尝试使用Bash getopts解析-temp
选项。我正在调用我的脚本:
./myscript -temp /foo/bar/someFile
以下是我用于解析选项的代码。
while getopts "temp:shots:o:" option; do
case $option in
temp) TMPDIR="$OPTARG" ;;
shots) NUMSHOTS="$OPTARG" ;;
o) OUTFILE="$OPTARG" ;;
*) usage ;;
esac
done
shift $(($OPTIND - 1))
[ $# -lt 1 ] && usage
答案 0 :(得分:46)
正如其他人所解释的那样,getopts不会解析长选项。你可以使用getopt,但它不是可移植的(它在某些平台上被破坏了......)
作为一种解决方法,您可以实现shell循环。这里是一个在使用标准getopts命令之前将长选项转换为short选项的示例(在我看来这更简单):
# Transform long options to short ones
for arg in "$@"; do
shift
case "$arg" in
"--help") set -- "$@" "-h" ;;
"--rest") set -- "$@" "-r" ;;
"--ws") set -- "$@" "-w" ;;
*) set -- "$@" "$arg"
esac
done
# Default behavior
rest=false; ws=false
# Parse short options
OPTIND=1
while getopts "hrw" opt
do
case "$opt" in
"h") print_usage; exit 0 ;;
"r") rest=true ;;
"w") ws=true ;;
"?") print_usage >&2; exit 1 ;;
esac
done
shift $(expr $OPTIND - 1) # remove options from positional parameters
答案 1 :(得分:40)
getopts
只能解析短选项。
大多数系统也有一个外部getopt
命令,但getopt不是标准的,并且通常被设计破坏,因为它不能安全地处理所有参数(带有空格和空参数的参数),只有GNU getopt可以安全地处理它们,但只有当你以GNU特定的方式使用它时。
更容易的选择是不使用,只需使用while循环迭代脚本的参数并自己进行解析。
答案 2 :(得分:2)
getopts
来解析仅1个字符的位置参数
(没有GNU风格的长选项(--myoption)或XF86风格的长选项(-myoption))
答案 3 :(得分:0)
你不能使用 getopts Bash内置的长选项 - 至少,不必构建自己的解析函数。您应该查看 / usr / bin / getopt 二进制文件(由我的系统util-linux包提供;您的里程可能会有所不同)。
有关特定的调用选项,请参阅getopt(1)。
答案 4 :(得分:0)
builtin bash getopts
确实只解析短选项,
但你仍然可以添加几行脚本来使getopts处理长选项。
以下是http://www.uxora.com/unix/shell-script/22-handle-long-options-with-getopts
中的部分代码 #== set options ==#
SCRIPT_OPTS=':fbF:B:-:h'
typeset -A ARRAY_OPTS
ARRAY_OPTS=(
[foo]=f
[bar]=b
[foobar]=F
[barfoo]=B
[help]=h
[man]=h
)
#== parse options ==#
while getopts ${SCRIPT_OPTS} OPTION ; do
#== translate long options to short ==#
if [[ "x$OPTION" == "x-" ]]; then
LONG_OPTION=$OPTARG
LONG_OPTARG=$(echo $LONG_OPTION | grep "=" | cut -d'=' -f2)
LONG_OPTIND=-1
[[ "x$LONG_OPTARG" = "x" ]] && LONG_OPTIND=$OPTIND || LONG_OPTION=$(echo $OPTARG | cut -d'=' -f1)
[[ $LONG_OPTIND -ne -1 ]] && eval LONG_OPTARG="\$$LONG_OPTIND"
OPTION=${ARRAY_OPTS[$LONG_OPTION]}
[[ "x$OPTION" = "x" ]] && OPTION="?" OPTARG="-$LONG_OPTION"
if [[ $( echo "${SCRIPT_OPTS}" | grep -c "${OPTION}:" ) -eq 1 ]]; then
if [[ "x${LONG_OPTARG}" = "x" ]] || [[ "${LONG_OPTARG}" = -* ]]; then
OPTION=":" OPTARG="-$LONG_OPTION"
else
OPTARG="$LONG_OPTARG";
if [[ $LONG_OPTIND -ne -1 ]]; then
[[ $OPTIND -le $Optnum ]] && OPTIND=$(( $OPTIND+1 ))
shift $OPTIND
OPTIND=1
fi
fi
fi
fi
#== options follow by another option instead of argument ==#
if [[ "x${OPTION}" != "x:" ]] && [[ "x${OPTION}" != "x?" ]] && [[ "${OPTARG}" = -* ]]; then
OPTARG="$OPTION" OPTION=":"
fi
#== manage options ==#
case "$OPTION" in
f ) foo=1 bar=0 ;;
b ) foo=0 bar=1 ;;
B ) barfoo=${OPTARG} ;;
F ) foobar=1 && foobar_name=${OPTARG} ;;
h ) usagefull && exit 0 ;;
: ) echo "${SCRIPT_NAME}: -$OPTARG: option requires an argument" >&2 && usage >&2 && exit 99 ;;
? ) echo "${SCRIPT_NAME}: -$OPTARG: unknown option" >&2 && usage >&2 && exit 99 ;;
esac
done
shift $((${OPTIND} - 1))
这是一个测试:
# Short options test
$ ./foobar_any_getopts.sh -bF "Hello world" -B 6 file1 file2
foo=0 bar=1
barfoo=6
foobar=1 foobar_name=Hello world
files=file1 file2
# Long and short options test
$ ./foobar_any_getopts.sh --bar -F Hello --barfoo 6 file1 file2
foo=0 bar=1
barfoo=6
foobar=1 foobar_name=Hello
files=file1 file2
否则在最近的Korn Shell ksh93中,getopts
可以自然地解析长选项,甚至可以显示手册页。 (见http://www.uxora.com/unix/shell-script/20-getopts-with-man-page-and-long-options)
Michel VONGVILAY。
答案 5 :(得分:0)
虽然这个问题是在2年前发布的,但我发现自己也需要支持XFree86风格的长选项;我也想从getopts中拿走我能做的。考虑GCC开关-rdynamic
。我将r
标记为标记字母,并期望dynamic
中的$OPTARG
...但是,我想拒绝-r dynamic
,同时接受r
之后的其他选项
我在下面提出的想法建立在观察$OPTIND
将大于其他情况,如果空格(间隙)跟随旗帜的话。因此,我定义了一个bash变量来保存前面的$OPTIND
值,称为$PREVOPTIND
,并在while
循环结束时更新它。如果$OPTIND
1
大于$PREVOPTIND
,我们就没有差距(即-rdynamic
);并且$GAP
设置为false
。如果$OPTIND
2
大于$PREVOPTIND
,我们做有差距(例如-r dynamic
),并设置$GAP
到true
。
usage() { echo usage: error from $1; exit -1; }
OPTIND=1
PREVOPTIND=$OPTIND
while getopts "t:s:o:" option; do
GAP=$((OPTIND-(PREVOPTIND+1)))
case $option in
t) case "${OPTARG}" in
emp) # i.e. -temp
((GAP)) && usage "-${option} and ${OPTARG}"
TMPDIR="$OPTARG"
;;
*)
true
;;
esac
;;
s) case "${OPTARG}" in
hots) # i.e. -shots
((GAP)) && usage
NUMSHOTS="$OPTARG"
;;
*) usage "-${option} and ${OPTARG}" ;;
esac
;;
o) OUTFILE="$OPTARG" ;;
*) usage "-${option} and ${OPTARG}" ;;
esac
PREVOPTIND=$OPTIND
done
shift $(($OPTIND - 1))
答案 6 :(得分:0)
感谢@mcoolive。
我能够使用您的$ @ idea将整个单词和长选项转换为单个字母选项。想要通知使用这个想法的任何人,我必须在通过getopts循环运行参数之前包含shift $(expr $OPTIND - 1)
。
目的完全不同,但效果很好。
# convert long word options to short word for ease of use and portability
for argu in "$@"; do
shift
#echo "curr arg = $1"
case "$argu" in
"-start"|"--start")
# param=param because no arg is required
set -- "$@" "-s"
;;
"-pb"|"--pb"|"-personalbrokers"|"--personalbrokers")
# pb +arg required
set -- "$@" "-p $1"; #echo "arg=$argu"
;;
"-stop"|"--stop")
# param=param because no arg is required
set -- "$@" "-S"
;;
# the catch all option here removes all - symbols from an
# argument. if an option is attempted to be passed that is
# invalid, getopts knows what to do...
*) [[ $(echo $argu | grep -E "^-") ]] && set -- "$@" "${argu//-/}" || echo "no - symbol. not touching $argu" &>/dev/null
;;
esac
done
#echo -e "\n final option conversions = $@\n"
# remove options from positional parameters for getopts parsing
shift $(expr $OPTIND - 1)
declare -i runscript=0
# only p requires an argument hence the p:
while getopts "sSp:" param; do
[[ "$param" == "p" ]] && [[ $(echo $OPTARG | grep -E "^-") ]] && funcUsage "order"
#echo $param
#echo "OPTIND=$OPTIND"
case $param in
s)
OPTARG=${OPTARG/ /}
getoptsRan=1
echo "$param was passed and this is it's arg $OPTARG"
arg0=start
;;
p)
OPTARG=${OPTARG/ /}
getoptsRan=1
echo "$param was passed and this is it's arg $OPTARG"
[[ "$OPTARG" == "all" ]] && echo -e "argument \"$OPTARG\" accepted. continuing." && (( runscript += 1 )) || usage="open"
[[ $( echo $pbString | grep -w "$OPTARG" ) ]] && echo -e "pb $OPTARG was validated. continuing.\n" && (( runscript += 1 )) || usage="personal"
[[ "$runscript" -lt "1" ]] && funcUsage "$usage" "$OPTARG"
arg0=start
;;
S)
OPTARG=${OPTARG/ /}
getoptsRan=1
echo "$param was passed and this is it's arg $OPTARG"
arg0=stop
;;
*)
getoptsRan=1
funcUsage
echo -e "Invalid argument\n"
;;
esac
done
funcBuildExcludes "$@"
shift $((OPTIND-1))
答案 7 :(得分:0)
如果您在使用内置<p><a href="#" onclick="window.open('http://google.com'); someTrackingFunction()";">Click to open Google and track this conversion</a></p>
时遇到麻烦,可以进行简单的DIY:
使用:
getopts
脚本:
$ ./test-args.sh --a1 a1 --a2 "a 2" --a3 --a4= --a5=a5 --a6="a 6"
a1 = "a1"
a2 = "a 2"
a3 = "TRUE"
a4 = ""
a5 = "a5"
a6 = "a 6"
a7 = ""
答案 8 :(得分:0)
最简单的方法是借助 getopt 和-longoptions
尝试一下,希望对您有用
# Read command line options
ARGUMENT_LIST=(
"input1"
"input2"
"input3"
)
# read arguments
opts=$(getopt \
--longoptions "$(printf "%s:," "${ARGUMENT_LIST[@]}")" \
--name "$(basename "$0")" \
--options "" \
-- "$@"
)
echo $opts
eval set --$opts
while true; do
case "$1" in
--input1)
shift
empId=$1
;;
--input2)
shift
fromDate=$1
;;
--input3)
shift
toDate=$1
;;
--)
shift
break
;;
esac
shift
done
这就是-您调用shell脚本
myscript.sh --input1 "ABC" --input2 "PQR" --input2 "XYZ"