Pengfei Song
Pengfei Song

Reputation: 33

Bash: How to capture error and echo value at the same time using local variable?

When I am trying to capture an error in a shellscript, if I use local variable to capture the echo value, the $? capturing the return value will always be 0 even if the function returns 1.

Why is that?

I can use global variable to address the issue, but I guess it violates the standard. Is there a better way to handle the error when I want to capture some echo value?

Thanks!

For example:

When using local variable:

test_error_handle() {
    echo "Some text"
    return 1
}
method() {
    local test=$(test_error_handle) # Use local variable
    echo "$?"
    echo ${test}
}
method

The output:

0
Some text

When using global variable:

test_error_handle() {
    echo "Some text"
    return 1
}
method() {
    test=$(test_error_handle) # Use local variable
    echo "$?"
    echo ${test}
}
method

The output:

1
Some text

Upvotes: 3

Views: 747

Answers (2)

user4918296
user4918296

Reputation:

Try this:

method() {
    local test
    test=$(test_error_handle) # Use local variable
    echo $?
    echo "${test}"
}

Keep the declaration on a separate line and the assignment on its own line. Then $? should hold the correct value.

Upvotes: 2

KamilCuk
KamilCuk

Reputation: 141060

Usually the exit status is the exit status of the last command executed.

local test=$(test_error_handle)

What happens here is that:

  • shell run the command test_error_handle
  • then shell runs the command local
  • local returns with zero exit status

So when you do echo $? you see the exit status of local command.

When you do:

test=$(test_error_handle)

the exit status of this expression is the exit status of the command substitution, that runs test_error_handle.

Upvotes: 3

Related Questions