【发布时间】:2018-05-18 06:41:35
【问题描述】:
我想将我的 getopt 调用放入一个函数中,这样我可以使我的脚本更整洁一些。我已经阅读了一些指南Using getopts inside a Bash function,但它们似乎是针对 getopts 而不是 getopt 并且无法理解它。
我的脚本开始时有以下 getopt 调用
#-------------------------------------------------------------------------------
# Main
#-------------------------------------------------------------------------------
getopt_results=$( getopt -s bash -o e:h --long ENVIRONMENT:,HELP:: -- "$@" )
if test $? != 0
then
echo "Failed to parse command line unrecognized option" >&2
Usage
exit 1
fi
eval set -- "$getopt_results"
while true
do
case "$1" in
-e | --ENVIRONMENT)
ENVIRONMENT="$2"
if [ ! -f "../properties/static/build_static.${ENVIRONMENT}.properties" -o ! -f "../properties/dynamic/build_dynamic.${ENVIRONMENT}.properties" ]; then
echo "ERROR: Unable to open properties file for ${ENVIRONMENT}"
echo "Please check they exist or supply a Correct Environment name"
Usage
exit 1
else
declare -A props
readpropsfile "../properties/dynamic/dynamic.${ENVIRONMENT}.properties"
readpropsfile "../properties/static/static.${ENVIRONMENT}.properties"
fi
shift 2
;;
-h | --HELP)
Usage
exit 1
;;
--)
shift
break
;;
*)
echo "$0: unparseable option $1"
Usage
exit 1
;;
esac
done
当我把所有的东西都放在函数中时,比如说叫parse_command_line ()
并使用parse_command_line "$@" 调用它
我的脚本死了,因为它无法计算出调用它的参数。我已经尝试按照一些指南将 OPTIND 设为本地。有什么建议吗?谢谢。
【问题讨论】:
-
显示你正在编写的exact函数,以及你得到的exact错误或结果。
-
参见BashFAQ #35,尤其是警告(靠近底部)永远不要使用
getopt。 -
请注意,
set -- arg arg arg在函数中完成将设置 函数 的位置参数,而不是“全局”位置参数。你需要做getopt_results=$(parse_command_line "$@"); eval set -- "$getopt_results",然后你就不会比现在更整洁了。 -
@AndyM, ...并且该帖子使用了大量不良做法,例如不兼容 POSIX 的
function关键字,不兼容的==比较运算符test,命令的反引号替换(不能很好地嵌套并改变其中反斜杠的行为)等(包括全大写变量名,POSIX 明确指定用于对 OS 和 shell 有意义的变量,而小写变量则保留给应用程序采用)。我在上面链接的 wiki 由 irc.freenode.org #bash 频道维护并反映了该频道的共识。 -
@AndyM, ...btw,我强烈推荐的另一个资源是the bash-hackers' wiki,它提供了a
getoptstutorial,同样反对反对getopt。