Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

python 2.7 - Bash: pass variable as a single parameter / shell quote parameter

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'

Quoting it doesn't do anything at all (well done, bash devs):

variable=Hello World
./program "$variable"
-> program receives: 'Hello' 'World'

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?

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?

Edit: No, I haven't tried

variable="Hello World"

because I never declare $variable. It's not being declared inside my bash function and I'm not allowed to modify it.

Edit: 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

did you try with var="hello world"?

i tried this in my solaris box.

> setenv var "hello world"
> cat temp.sh
#!/bin/sh

echo $1
echo $2
> ./temp.sh "$var"
hello world

>

as you can see the $2 is not printed.$var is considered as only one argument.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...