Reputation: 7863
Given the following two executable scripts:
----- file1.sh
#!/bin/sh
. file2.sh
some_routine data
----- file2.sh
#!/bin/sh
some_routine()
{
#get the data passed in
localVar=$1
}
I can pass 'data' to a subroutine in another script, but I would also like to return data.
Is it possible to return information from some_routine?
e.g: var = some_routine data
Upvotes: 2
Views: 4255
Reputation: 445
if
some_routine() {
echo "first"
echo "foo $1"
}
some_var=$(some_routine "second")
echo "result: $some_var"
they are ok.But the result seems to be decided by the first "echo".Another way is use "eval". some_var return "first"
some_routine()
{
echo "cmj"
eval $2=$1
}
some_routine "second" some_var
echo "result: $some_var"
in this way, some_var return "second".The bash don't return a string directly.So we need some tricks.
Upvotes: 0
Reputation: 1569
It's not allowed, just set the value of a global variable (..all variables are global in bash)
Upvotes: 0
Reputation: 526643
Have the subroutine output something, and then use $()
to capture the output:
some_routine() {
echo "foo $1"
}
some_var=$(some_routine bar)
Upvotes: 8