ls to list directory contents, it typically returns an exit code of 0 to indicate success:
lss—results in an error message and a non-zero exit code:
Custom Command Example: Rocket Commands
The same principles apply to custom commands. Consider a command namedrocket-status used to check the status of a rocket launch. This command returns an exit code of 0 if the launch is successful and 1 if it fails:
$?. It is important to execute echo $? immediately after running the command, as any subsequent command may modify its value.
Always check the exit code immediately after running a command using
echo $? to ensure you capture the correct value.Best Practices for Scripts
It is best practice for scripts—especially those integrated with other scripts—to return appropriate exit codes that signal success or failure. Consider the following example script for launching a rocket:- Various setup steps are executed for initiating the mission.
- The script continuously checks the rocket’s status until it is no longer “launching”.
- If the status changes to “failed”, the script runs
rocket-debugand explicitly exits with an exit code of 1.
Without the
exit 1 command in the failure block, the script would default to an exit code of 0 even when the launch fails, which can lead to improper error handling.