While applying the Google Shell Style Guide on some bash code, I learned that I do not exactly know how to determine the exit state of a function. In particular, I was wondering whether any successful bash function returns the state 0, or whether it is only certain commands that ensure it returns state 0.
The example given:
#######################################
# Delete a file in a sophisticated manner.
# Arguments:
# File to delete, a path.
# Returns:
# 0 if thing was deleted, non-zero on error.
#######################################
function del_thing() {
rm "$1"
}
Describes the rm
action, which apparently results in a state 0. However, I wonder whether all other commands that do not lead to an error also return state 0. (Excluding specific commands to set a specific return state like exit 42
).
To find this out, I'd like to inspect the return state of certain functions. Yet I do not yet exactly know how to do that. Hence, I would like to ask: How do I print/see/inspect the return state of a function?
CodePudding user response:
How do I print/see/inspect the return state
The variable $?
hols the exit status of the previous command.
literally anything
echo "$?"
del_thing
echo "$?"
Note: do not use $?
when checking for failure or success. Use if
, like if ! del_thing; then echo "it failed"; fi
.
Note: Do not use function
with ()
. Just use name() { .. }
, without function
. See https://wiki.bash-hackers.org/scripting/obsolete . (https://github.com/google/styleguide/pull/624 ..)
I wonder whether all other commands that do not lead to an error also return state 0
0
exit status is considered success. Nonzero exit status is considered failure. For example, if
expression checks if a command has a zero exit status - if anything; then echo "anything exited with zero exit status"; fi
.
A function has the exit status of the last command executed. Usually, anything has the exit status of the last command executed. The exit status of del_thing
function is the same as the exit status of rm
command, because rm
command is the last thing executed inside the function.