击:传递变量作为一个参数/壳报价参数 [英] Bash: pass variable as a single parameter / shell quote parameter
问题描述
我正在写有传递到另一个程序变量的bash脚本:
I'm writing a bash script which has to pass a variable to another program:
./program $variable
的问题是,这是绝对必要的$变量作为一个单一的参数,如果它包含空白这不是的情况下通过。
The problem is, it is absolutely necessary for $variable to be passed as a single parameter, which isn't the case if it contains whitespace.
variable=Hello World
./program $variable
-> program receives two arguments: 'Hello' 'World'
引用它不会做所有事情(做得很不错,bash的开发者):
Quoting it doesn't do anything at all (well done, bash devs):
variable=Hello World
./program "$variable"
-> program receives: 'Hello' 'World'
双引号它疯狂的东西(做得很好,bash的开发者):
Double quoting it does crazy stuff (well done, bash devs):
variable=Hello World
./program "'$variable'"
-> program receives: "'Hello" "World'"
有没有一种简单的方法来做到这一点?哎呀,有没有办法做到这一点呢?
Is there an easy way to do this? Heck, is there a way to do this at all?
更新:好吧,因为这个问题似乎并没有被bash的,这里的一些额外的信息。
我传递参数给程序是一个python脚本。不以任何方式修改参数,我得到
Update: Okay, since the problem doesn't seem to be bash, here's some additional info. The program I'm passing arguments to is a python script. Without modifying the arguments in any way, I get
print sys.argv
-> ['/usr/bin/program', "'Hello", "World'"]
我该如何解决呢?
How can I fix that?
编辑:否,我没试过
variable="Hello World"
因为我从来没有申报$变量。它没有被宣告我的bash函数里面,我不允许修改它。
because I never declare $variable. It's not being declared inside my bash function and I'm not allowed to modify it.
编辑:好吧,我得到它的工作方式
Okay, I got it to work that way.
local temp="$variable"
./program "$temp"
我想知道它为什么这样工作,而不是任何其他方式,但。
I'd like to know why it works that way and not any other way, though.
推荐答案
这个问题似乎是方案在
variable="Hello World" # quotes are needed because of the space
./program "$variable" # here quotes again
和里面的程序
echo "program received $# arguments:"
i=1
for arg in "$@" # again quotes needed
do echo "arg $((i=i+1)): '$arg'" # and again
done
这篇关于击:传递变量作为一个参数/壳报价参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!