0

In function_two, I need to get both the output from echo and the return value from function_one

#!/bin/bash
function_one() {
    echo "okay then"
    return 2
}
function_two() {
    local a_function="function_one"
    local string=`${a_function}`
    echo $string # echos "okay then"
    echo "$?" #echos 0 - how do we get the returned value of 2?
}
function_two

When trying echo "$?" I get 0 instead of 2

Update

As Ipor Sircer pointed out, $? above is giving the exit code of the previous command echo $string

So instead I grab the exit code immediately after. And as choroba mentioned, the localization and assignment of the variable needed to be separated.

Here is the working script:

#!/bin/bash
function_one() {
    echo "okay then"
    return 2
}
function_two() {
    local a_function="function_one"
    local string
    string=`${a_function}`
    local exitcode=$?
    echo "string: $string" # okay then
    echo "exitcode: $exitcode" # 2
}
function_two
1
  • 1
    the echo $string command has run successfully, so the exitcode is 0. Commented Jan 16, 2017 at 22:25

1 Answer 1

6

0 is the exit status of the last command executed, i.e. echo $string.

If you need to use the exit status later, store it in a variable:

local string
string=`${a_function}`
local status=$?
echo "Output: $string"
echo "Status: $status"

You also need to separate the assignment and localization of the variable to not get the status of local instead.

Sign up to request clarification or add additional context in comments.

2 Comments

Status is still 0 instead of 2. Losing the status from function_one since it's executed in a sub process with backtick
@asdfqwerzxcv: No, it's because you're getting the status of local. See the updated answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.