解析 bash 脚本中包含空格的输入选项
我有一个 bash 脚本解析输入选项,其中包含如下代码块
for WORD in "$@" ; do
case $WORD in
--*) true ;
case $WORD in
--opt1=*)
OPT1=${WORD/--opt1=/}
shift ;;
--opt2=*)
OPT2=${WORD/--opt2=/}
shift ;;
*) echo "Unrecognized argument $WORD"
;;
esac ;;
*) echo "Option $WORD not starting with double dash."
;;
esac
done
该脚本由另一个创建整个命令行的父程序调用。 该父程序创建的输出看起来像
./childscript.sh "--opt1=value1 --opt2=value2"
当生成的行看起来像这样时,就会出现问题
./childscript.sh "--opt1='value11 value12' --opt2=value2"
脚本抱怨说
Option value12 not starting with double dash.
如何修改子 bash 代码以使其理解输入选项内的空格?
I have a bash script parsing input option with a block of code like the following
for WORD in "$@" ; do
case $WORD in
--*) true ;
case $WORD in
--opt1=*)
OPT1=${WORD/--opt1=/}
shift ;;
--opt2=*)
OPT2=${WORD/--opt2=/}
shift ;;
*) echo "Unrecognized argument $WORD"
;;
esac ;;
*) echo "Option $WORD not starting with double dash."
;;
esac
done
The script is invoked by another parent program which creates the entire command line.
The output created by this parent program looks like
./childscript.sh "--opt1=value1 --opt2=value2"
The problems appear when the generated line looks like
./childscript.sh "--opt1='value11 value12' --opt2=value2"
The scripts complains saying
Option value12 not starting with double dash.
How can I modify the child bash code to make it understand white spaces inside the input options?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不认为生成的线是你想象的那样。
如果我直接调用它,你的代码对我来说完全可以正常工作。通过添加回声来检查值是否存储在正确的位置:
您应该能够确认这一点。您的问题不在于使子脚本接受此类参数,而在于让父脚本正确调用它。
顺便说一句,您实际上并不想运行这样的代码:
这将导致整个字符串 (
--opt1=value1 --opt2=value2
)被解读为单个参数。我怀疑您还没有告诉我们父脚本调用此方法的完整故事。如果您向我们展示这些详细信息,我们可能可以提供更多帮助 - 或者这可能已经足够了。I don't think the generated line is what you think it is.
Your code works completely fine for me if I simply invoke it directly. With added echoes to check that the values are being stored in the right place:
You should be able to confirm this. Your problem isn't in making the child script accept arguments like these, it's in having the parent script invoke it correctly.
And by the way, you don't actually want to run something like this:
That will cause that entire string (
--opt1=value1 --opt2=value2
) to be read as a single argument. I suspect that you haven't told us the full story on the way the parent script is calling this. If you show us those details, we can probably help out more - or maybe this is enough of a hint.