To check the exit code of command in Bash the following logic is used:
if [ $? -ne 0 ]
then
echo "Error occurred"
return 1
fi
My problem is that adding this after every command makes the script very long with multiple copies of the same thing, and very hard to maintain.
The best thing here would be a function, that would be called from all the locations the the exit code needs to be checked. The problem is that the exit
command can not be used, because it will kill current process (current Bash session will be killed), so only the return
command can be used. But when using the return command, in a called function, the calling function must still check the exit code, and were back to the same problem.
Is there any thing like MACRO in Bash or any other way to the error checking more efficient?
Instead of this:
You don't need to write conditions on the
$?
variable, you can use the command itself inif
statements:Another alternative is to create a helper function to encapsulate the action on error, and use the
||
operator after the command to call the function and thenreturn 1
after:Finally, if you don't really need
return 1
and you don't mind to exit the script in case of failure, then you canexit 1
inside the helper function and then the caller code can become more compact: