What Exit Codes Does Sudo Return in Ubuntu?
When working with scripts or troubleshooting permissions in Ubuntu, understanding the exit status of the sudo command is essential for automation and error handling. This article explains the standard exit codes returned by sudo, distinguishes between sudo failures and command failures, and provides methods to verify these statuses in your terminal. You will learn how to interpret success, authentication errors, and command execution results effectively.
General Exit Code Behavior
The sudo command primarily acts as a wrapper for other commands. Consequently, its default behavior is to return the exit code of the command it executes. If the command runs successfully, sudo returns 0. If the command runs but encounters an error, sudo returns the specific error code generated by that command. This pass-through mechanism allows scripts to detect failures in the underlying task rather than just the privilege escalation process.
Sudo-Specific Failure Codes
When sudo itself fails to execute the command due to permission issues or authentication errors, it typically returns an exit code of 1. This occurs in scenarios such as incorrect password entry, the user not being listed in the sudoers file, or policy restrictions preventing the action. Unlike the executed command, these codes indicate that the privilege escalation failed before the target command could even start.
Verifying Exit Codes
To check the exit code of the last executed command in Ubuntu, use the echo $? command immediately after running sudo. For example, running sudo ls /root followed by echo $? will display 0 if successful. If authentication fails, the same check will return 1. Incorporating this check into bash scripts using if statements ensures that your automation logic responds correctly to permission denied errors versus command execution errors.