• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer navigation

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • VCS
  • Interview Questions
  • Database
    • MariaDB
  • DevOps
    • Docker
    • Shell Scripting
  • Big Data
    • Hadoop
    • Cloudera
    • Hortonworks HDP

How to use Exit Codes in Conditional Statements in Shell Scripts

by admin

The exit Command

You can use the exit command in a script to force the shell to terminate with whatever exit code you provide. For example, exit 1 will cause the script to terminate with a failure status. If you don’t provide a number, exit will terminate with the exit code of the last command that was run.

Using exit codes in Conditional Statements

Conditional statements like if…else are good at handling process exit codes. For example:

chmod 888 file 2> /dev/null

if [ $? -eq 0 ]
then
    echo "Permissions set successfully."
    exit 0 
else
    echo "Could not set permissions."
    exit 1 
fi

If the chmod command exits with a code of 0, then the success message is echoed to the screen, and any other process that executes this script will receive that exit code because of the exit command. Likewise, if the exit code is 1, then a custom error message is echoed to the screen. The default error message is suppressed, as it is being redirected to the null device.

Filed Under: Linux

Some more articles you might also be interested in …

  1. flutter: Google’s free, open source, and cross-platform mobile app SDK
  2. Linux rsync command with practical examples
  3. Examples of creating command alias in different shells
  4. xrpd: command not found
  5. assimp: Command-line client for the Open Asset Import Library
  6. Understanding OpenSSH Configuration Files
  7. rofi: command not found
  8. getent: command not found
  9. lpr Command Examples
  10. shred: command not found

You May Also Like

Primary Sidebar

Recent Posts

  • Vanilla OS 2 Released: A New Era for Linux Enthusiasts
  • mk Command Examples
  • mixxx Command Examples
  • mix Command Examples

© 2025 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright