bash bash中的参数解析
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14152712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Argument parsing in bash
提问by Reuben
I am new to bash. Need suggestion for the following problem.
我是 bash 新手。需要针对以下问题提出建议。
So I want to execute the script in this way
所以我想以这种方式执行脚本
./myscript --bootstrap bootstrap.exe --vmmount ./vmmount --image /dev/sdb2 --target-exe installer.exe [--internal-exe] param1 param2 param3 ...
Argument parser i have done:
我做过的参数解析器:
VMMOUNT=""
BOOTSTRAP=""
IMAGE_FILE=""
TARGET_EXE=""
INTERNAL_EXE=""
while : ; do
if [ "" = "--vmmount" ] ; then
[ -n "${VMMOUNT}" ] && usage
VMMOUNT=""
shift
shift
elif [ "" = "--bootstrap" ] ; then
[ -n "${BOOTSTRAP}" ] && usage
BOOTSTRAP=""
shift
shift
elif [ "" = "--image" ] ; then
[ -n "${IMAGE_FILE}" ] && usage
IMAGE_FILE=""
shift
shift
elif [ "" = "--target-exe" ] ; then
[ -n "${TARGET_EXE}" ] && usage
TARGET_EXE=""
shift
shift
elif [ "" = "--internal-exe" ] ; then
[ -n "${INTERNAL_EXE}" ] && usage
INTERNAL_EXE="true"
shift
shift
else
break
fi
done
my_method "${IMAGE_FILE}" "${VMMOUNT}" "${BOOTSTRAP}" "${TARGET_EXE}" "${INTERNAL_EXE}"
Now I have confusion in parsing the parameters param1 and param2 etc. How to parse them ? Can I use $@to take the params as array or any other efficient way ?
现在我在解析参数 param1 和 param2 等时感到困惑。如何解析它们?我可以$@用来将参数作为数组或任何其他有效方式吗?
采纳答案by Barmar
VMMOUNT=""
BOOTSTRAP=""
IMAGE_FILE=""
TARGET_EXE=""
INTERNAL_EXE=""
while : ; do
case "" in
--vmmount)
[ -n "${VMMOUNT}" ] && usage
VMMOUNT=""
shift 2 ;;
--bootstrap)
[ -n "${BOOTSTRAP}" ] && usage
BOOTSTRAP=""
shift 2 ;;
--image)
[ -n "${IMAGE_FILE}" ] && usage
IMAGE_FILE=""
shift 2 ;;
--target-exe)
[ -n "${TARGET_EXE}" ] && usage
TARGET_EXE=""
shift 2 ;;
--internal-exe)
[ -n "${INTERNAL_EXE}" ] && usage
INTERNAL_EXE="true"
shift ;;
*)
break ;;
esac
done
my_method "${IMAGE_FILE}" "${VMMOUNT}" "${BOOTSTRAP}" "${TARGET_EXE}" "${INTERNAL_EXE}" "$@"
Don't forget to enclose $@in double quotes.
不要忘记$@用双引号括起来。
回答by Karthik T
I would suggest you use getoptto parse your command line arguements instead of hand coding it. It should save a lot of time.
我建议你使用getopt来解析你的命令行参数,而不是手动编码。它应该可以节省很多时间。
Also shown in How do I parse command line arguments in Bash?

