Reputation: 33
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
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
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:
test_error_handle
local
local
returns with zero exit statusSo 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