0

Similar to How can I assign the output of a function to a variable using bash?, but slightly different.

If I have a function like this:

function scan {
  echo "output"
}

...I can easily assign this to a variable like this:

VAR=$(scan)

Now, what if my function takes one or more parameters, how can I pass them to the function using the "shell expansion" syntax? E.g. this:

function greet {
  echo "Hello, $1"
}

# Does not work
VAR=$(greet("John Doe"))

The above produces an error like this with my bash (version 5.0.3(1)-release):

$ ./foo.sh 
./foo.sh: command substitution: line 8: syntax error near unexpected token `"John Doe"'
./foo.sh: command substitution: line 8: `greet("John Doe"))'

2 Answers 2

2

in this code :

function greet {
  echo "Hello, $1"
}

# Does not work
VAR=$(greet("John Doe"))

the error is the parenthesis passing parameters. try to do this:

function greet {
  echo "Hello, $1"
}

# works
VAR=$(greet "John Doe")

it should work.

Explanation: when you use the $ an the parenthesis you have to write inside the parenthesis command as in a shell so the parameters are passed without parenthesis.

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

4 Comments

Thanks. I already documented this (at the same time as writing the question) here: stackoverflow.com/a/59388263/227779 :-)
Why would I upvote it when it mostly just duplicates my answer which was written before? I discovered the answer to my question while writing it, but decided to write down the answer Q&A-style. Thanks for writing a reply, but your answer doesn't add much more than what my answer already stated.
Oh sorry, i don't see your answer from my mobile. Regards
Fair enough. I will upvote your answer now in good will. :) Merry Christmas!
0

I have obviously been writing to much Java code lately. Drop the parentheses when calling the function and everything works flawlessly:

function greet {
  echo "Hello, $1"
}

VAR=$(greet "John Doe")

Comments

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.