0

Could be possible to use predefined variable after function is executed. Ex.:

var="host1 host2"
function test {
echo $1
echo $2
}
test var host3

Expected result should to be:

host1 host2 
host3

Not sure how use define that variable like local or something else ...

1
  • 1
    test "$var" host3 ?? Commented Aug 9, 2017 at 11:52

1 Answer 1

3

You can have this code in your function with indirect variable reference

testfn() {
   for v; do
      echo "${!v:-$v}"
   done
}

var="host1 host2"

then call it as:

testfn var host3

which will print this output:

host1 host2
host3

Expression "${!v:-$v}" attempts to reference a variable with the string contained in $v and if it is not set then used $v (which is positional argument string).

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

4 Comments

Probably you are right. I posted it in case OP wants it the way it is shown in question.
I just deleted my answer to make this de-facto!
@Inian No you should keep your answer as that is simple and it might resolve OP's problem.
Nah! this is more comprehensive, just do an edit of yours with that!

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.