2

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
1
  • Just fyi, you can't have a space in the assignment: `var=$(some_routine data) Commented Mar 14, 2012 at 23:12

3 Answers 3

8

Have the subroutine output something, and then use $() to capture the output:

some_routine() {
    echo "foo $1"
}

some_var=$(some_routine bar)
Sign up to request clarification or add additional context in comments.

2 Comments

This and other solutions are discussed at linuxjournal.com/content/return-values-bash-functions
Thank-you for the responses. The option provided by Amber works, but not in my case. My routines echo various status messages and can return an early response. I tried the second option under the link that jofel provided and it works perfectly for me. jofel, can you please respond to my question with that answer? I will mark it as the solution.
0

It's not allowed, just set the value of a global variable (..all variables are global in bash)

Comments

0

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.

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.