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

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • Solaris
    • Oracle Linux
    • VCS
  • Interview Questions
  • Database
    • oracle
    • oracle 12c
    • ASM
    • mysql
    • 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. htop (interactive process viewer) Linux Performance Monitoring tool
  2. sa Command Examples in Linux
  3. RPM command examples to query, install, remove and upgrade packages
  4. Linux OS Service ‘network’
  5. ‘lxc_cgfs – Device or resource busy – failed to set memory.use_hierarchy to 1; continuing’ – error while starting LXC container
  6. Linux “shutdown”, “poweroff”, “halt”, “reboot” Commands
  7. How to Rebuild the “initramfs” with Multipath in CentOS/RHEL 6 and 7
  8. synopkg Command Examples in Linux
  9. mimetype: command not found
  10. qsub: command not found

You May Also Like

Primary Sidebar

Recent Posts

  • aws ec2: CLI for AWS EC2 (Command Examples)
  • aws cur – Create, query, and delete AWS usage report definitions (Command Examples)
  • aws configure – Manage configuration for the AWS CLI (Command Examples)
  • aws cognito-idp: Manage Amazon Cognito user pool and its users and groups using the CLI

© 2023 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright