2

say we have:

test() {
    echo $1
    echo $2
}

and two variables:

a="hello world"
b="$a blabla.."

test $b

it displays:

hello
world

what I want is:

hello world
blabla..

How can I achieve this?

Thanks

2
  • I'm not a shell expert, but can't you just do echo $1, $2 Commented May 14, 2014 at 9:04
  • @ArashSaidi if I do echo $1, $2 in test(), I get 'hello, world'. But What I want is 'hello world, blabla..' Commented May 14, 2014 at 9:07

2 Answers 2

2

Use this:

a="hello world"
b="'$a' blabla"
eval "test $b"

The single-quotes are needed to keep hello world together as a single argument. Then you need to use eval because quotes are not normally processed after variable expansion.

Sign up to request clarification or add additional context in comments.

3 Comments

You should only use eval if your shell does not support arrays (for instance, you require POSIX compatibility).
It depends on where the values are coming from, and how they're being put together into the variable.
It seems that if you have the ability to control the format of b, you also have the ability to make b an array instead. I'm not sure what other situation would preclude the use of an array.
2

You want b to be an array, otherwise there's no way with a single string containing whitespace to determine which space char is the separator:

mytest() {
    echo "$1"
    echo "$2"
}

a="hello world"
b=( "$a" "blah blah" )

mytest "${b[@]}"
hello world
blah blah

2 Comments

A very interesting approach
+1 Also the correct approach, as this is why shells add support for arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.