Reputation: 4220
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"))'
Upvotes: 0
Views: 1702
Reputation: 3535
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.
Upvotes: 2
Reputation: 4220
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")
Upvotes: 0