TERACytE
TERACytE

Reputation: 7863

How to return data from a bash shell script subroutine?

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

Answers (3)

Umae
Umae

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

kappa
kappa

Reputation: 1569

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

Upvotes: 0

Amber
Amber

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

Related Questions