Reputation: 13
I am writing a backup bash script, and organize it as a set of several .sh files (each of them executing one function) that are called from the main .sh file (like libraries in any conventional PL). One of them is a logging script that is to take an exit code of the previously executed command and if it succeeds the script logs one message, and if it doesn't - logs another.
However, if I check $? within the logging script, I always get 0 code regardless of the previous command's result in the main script. As far as I understand the process, calling the script from an outer file makes it being executed in a different subshell that has $? with 0 value as nothing failed within that very subshell.
#main.sh:
command; log.sh "message" "error"
#log.sh:
if [ "${?}" -eq "0" ]; then
printf "${1}\n" >> main.log
else
printf "${2}\n" >> main.log
fi
The $? is always 0, so it always logs a success message. How do I get the actual exit code of the "command" above?
I might store it in some file and read the file in the beginning of the log.sh, but I feel there is a better solution.
Upvotes: 1
Views: 69
Reputation: 42999
As stated by you, since log.sh
is a script, it executes in a separate shell and hence $?
of the caller is not visible to it. When a script starts, $?
is 0 initially.
You can wrap your logging functionality into a function so that $?
is visible to it:
log() {
if [ "${?}" -eq "0" ]; then
printf "${1}\n" >> main.log
else
printf "${2}\n" >> main.log
fi
}
But it is better to pass $?
explicitly as suggested by @cyrus.
You may want to take a look at the logging and error handling functionality implemented here:
https://github.com/codeforester/base/blob/master/lib/stdlib.sh
Upvotes: 2
Reputation: 88553
Replace
command; log.sh "message" "error"
with
command; log.sh "message" "error" "$?"
and
if [ "${?}" -eq "0" ]; then
with
if [ "$3" -eq "0" ]; then
Upvotes: 2