通过bash中的变量将标志传递给命令 [英] Passing flags to command via variables in bash
问题描述
我有一个复杂的脚本,该脚本从文件中获取变量,并使用它们来运行程序(特别是葡萄酒")
I have a complex script that takes variables from files and uses them to run programs (Wine specifically)
从另一个文件中的变量传递选项无法按预期进行:
Passing options from the variables in the other file isn't working as expected:
#!/bin/bash
. settingsfile
wine $run
在另一个文件中:
run="run.exe -withoption \"This text\""
当我将wine $run
更改为echo wine $run
时,它将回显一个字符串,该字符串在明确运行时可以正常工作:
When I change wine $run
to echo wine $run
, it echos a string, which when run explicitly works fine:
#!/bin/bash
. settingsfile
wine run.exe -withoption "This text"
使用#!/bin/bash -x
运行会显示:
+ wine run.exe -withoption '"This' 'text"'
我该如何解决?
推荐答案
问题是"This
和text"
被视为单独的参数,每个参数都包含双引号,而不是单个参数This text
.如果编写一个函数以每行打印一个参数,您会看到这一点.这个:
The problem is that "This
and text"
are treated as separate arguments, each containing a double-quote, rather than as a single argument This text
. You can see this if you write a function to print out one argument per line; this:
function echo_on_separate_lines ()
{
local arg
for arg in "$@" ; do
echo "<< $arg >>"
done
}
run="run.exe -withoption \"This text\""
echo_on_separate_lines $run
打印此:
<< run.exe >>
<< -withoption >>
<< "This >>
<< text" >>
而不是这个:
<< run.exe >>
<< -withoption >>
<< This text >>
最简单的解决方案是使用eval
重新处理报价:
The simplest solution is to tack on an eval
to re-process the quoting:
run="run.exe -withoption \"This text\""
wine $run # or better yet: wine "$run"
但是更可靠的解决方案是将run
设为数组,然后可以将其称为"${run[@]}"
:
But a more robust solution is to have run
be an array, and then you can refer to it as "${run[@]}"
:
run=(run.exe -withoption "This text")
wine "${run[@]}"
以便从一开始就正确处理报价.
so that the quoting is handled properly from the get-go.
这篇关于通过bash中的变量将标志传递给命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!