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
714 views
in Technique[技术] by (71.8m points)

linux - Bash pass variable as argument with quotes

Assume ./program is a program that just prints out the parameters;

$ ./program "Hello there"
Hello there

How can I properly pass arguments with quotes in from a variable? I am trying to do this;

$ args='"Hello there"'  
$ echo ${args}  
"Hello there"  
$ ./program ${args}  
Hello there # This is 1 argument

but instead, when I go through a variable the quotes in args seem to be ignored so I get;

$ args='"Hello there"'
$ echo ${args}
"Hello there"
$ ./program ${args}
"Hello there" # This is 2 arguments

Is it possible to have bash treat the quotes as if I entered them myself in the first code block?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

I don't know where you got program from, but it appears that it's broken. Here's a correct way to write it in bash:

#!/bin/bash

for arg in "$@"; do
    echo "$arg"
done

This will print each argument in a separate line to make them easier to distinguish (it will of course have a problem with arguments that contain a line break, but we will not pass such an argument).

After you have saved the above as program and gave it the execute permission, try this:

$ args='"Hello there"'
$ ./program "${args}"
"Hello there"

whereas

$ args='"Hello there"'
$ ./program ${args}
"Hello
there"

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

...