How do exit statuses work?

097

Exit statuses are numerical codes returned by commands or scripts in a Unix-like operating system, indicating the success or failure of the command's execution. Here's how they work:

Basic Concepts

  1. Exit Status Code:

    • Every command returns an exit status code when it finishes executing.
    • By convention, an exit status of 0 indicates success, while any non-zero value indicates an error or failure.
  2. Checking Exit Status:

    • You can check the exit status of the last executed command using the special variable $?.
    • For example:
      command
      echo $?
    • This will print the exit status of command.

Common Exit Status Codes

  • 0: Success
  • 1: General error (catch-all for miscellaneous errors)
  • 2: Misuse of shell builtins (e.g., syntax errors)
  • 126: Command invoked cannot execute (permission issues)
  • 127: Command not found
  • 128: Invalid argument to exit
  • 130: Script terminated by Ctrl+C (SIGINT)
  • Other codes can be defined by specific commands or scripts to indicate different types of errors.

Usage in Scripts

Exit statuses are often used in scripts to control the flow of execution. For example:

#!/bin/bash

command1
if [ $? -eq 0 ]; then
    echo "command1 succeeded."
else
    echo "command1 failed."
fi

Using with Conditional Statements

You can use exit statuses in conditional statements to determine the next steps in a script:

command1 && command2  # command2 runs if command1 succeeds
command1 || command2  # command2 runs if command1 fails

Summary

  • Exit statuses provide a way to determine the outcome of command execution.
  • A status of 0 indicates success, while non-zero values indicate various types of errors.
  • They are essential for error handling and control flow in shell scripts.

0 Comments

no data
Be the first to share your comment!