artella
artella

Reputation: 5118

Calling one function within another function

I am trying to call one bash function from within another bash function and it is not working as expected :

#/bin/bash
function func1(){
    echo "func1 : arg = ${1}"
    return 1
}
function func2(){
    echo "func2 : arg = ${1}"
    local var=func1 "${1}"
    echo "func2 : value = $var"
}
func2 "xyz"

and the current output is :

Current output :
func2 : arg = xyz
func2 : value = func1

Question : how can I modify the program above so as to get the following output ? :

Desired output : 
func2 : arg = xyz
func1 : arg = xyz
func2 : value = 1

Upvotes: 2

Views: 3189

Answers (3)

fflores
fflores

Reputation: 442

This note may be useful because it is related somehow, the keyword return in function is used to return not the value, but the status of the function (fail or success):

function fun() {
    return 1
}

if ! fun; then
    echo "Fail"
fi

Also, keep in mind that by default any function returns the exit code of the last command that was executed by that function:

function fun() {
   echo "hello, World!"
   cat some_file_that_does_not_exist # exit code 1
}

if ! fun; then
    echo "Fail"
fi

But for your task, @choroba gave you the right answer.

Upvotes: 0

choroba
choroba

Reputation: 241858

Change func2 definition to the following:

function func2 () {
    echo "func2 : arg = ${1}"
    func1 "${1}"
    local var=$?
    echo "func2 : value = $var"
}

Upvotes: 2

cdarke
cdarke

Reputation: 44354

Functions in Bash do not work in the same way as functions in many other languages, they can only return an integer between 0 and 255. This is grabbed using $? after the function call. If you want to get some other value, for example a string, call it in a sub-shell:

local var=$(func1 "${1}")

will get the stdout (from echo statements) from the function into $var.

By the way, function syntax is:

function func1 { ... }

or

func1() { ... }

Upvotes: 5

Related Questions