A string within a string in shell

2019-08-30 07:41发布

问题:

Below line is the sample of my code

command mycommand /path/location arg1="my valu1" arg2="my value2"

when I am executing this command by hard-coding the argument value it works.

But when I am using below code format:

for i in "$@" do
str+="$i " 
done
command mycommand /path/location $str

where $str="arg1="my valu1" arg2="my value2""

It is not accepting "my value1" as a single string. It is taking "my" as one string and "value2" as a separate string.

Now if I use

command mycommand /path/location "$str"

then $str="arg1="my valu1" arg2="my value2"" as only one complete string. But I want command should execute in below format through program way.

command mycommand /path/location arg1="my valu1" arg2="my value2"

How to do this?

回答1:

Don't try to append your arguments into a string just pass along "$@" to your actual command inside the script:

command mycommand /path/location "$@"


回答2:

In a shell which supports arrays (eg, bash), you would use an array:

command mycommand /path/location "${arr[@]}"

If your shell doesn't support arrays, you can use the positional paramters:

command mycommand /path/location "${@}"

A common hack is to use set reset the positional parameters. That is, you can do:

set -- "arg one" "arg two"


标签: shell unix