Skip to main content

Command Palette

Search for a command to run...

Getting Started with If-Else and Exit Status

Published
2 min read
Getting Started with If-Else and Exit Status
I

An enthusiast about continuously broadening my horizons in the dynamic world of technology.

Exit Codes

Every command we run on bash script return an exit status/ return codes. These range from 0 to 255 with 0 being SUCCESS. Codes other than 0 are error codes.

  • To find the meaning of exit status we can use “man” or “info”.

  • $? is used to check the exit status from most recent run command.

Lets say i want to check what is “ping” doing here i will write man ping and below page will open

If-Else Conditions

Below is the template to write your if else condition :

Important points to remember -

  • Always put space before and after “condition”

  • Always write “then” in next line.

  • fi marks the end of if-else condition.

if [ write-your-condition ]

then

echo "your output"

elif [ write-your-condition ]

then

echo "your output"

else

echo "your output"

fi

Setting Up Your Own Exit Command

We can set up our own exit command explicitly but if there is not exit command set up then the value returned will be the default of the last command.

When the condition reaches the exit status the code stops even if the condition is not completed. (we will see this condition in later articles)

In the below given example if have set exit status as 20 is condition is correct and exit status 30 if condition is not correct.

Others Operators

Using && and ||

&& = AND

When we use && then the condition following the operator only gets executed if and only if the return code of first condition is 0.

|| - OR

When we use && then the condition following the operator only gets executed if the return code of first condition is 1.

Semicolon

If the commands are separated using a semicolon (;), this ensures that the following command gets executed whether the first command runs successfully or not.

You can find all the scripts mentioned in this article in the repository below:

https://github.com/ishaj72/Bash-Scripting

Stay tuned for the next article, where we will explore For Loops and Positional Parameters in Bash scripting.

Happy reading!!

Bash Scripting

Part 2 of 4

This series introduces you to the basics of Bash scripting, guiding you through essential commands, script syntax, and automation techniques. Ideal for beginners aiming to build a foundation in shell scripting.

Up next

Operators In Bash Scripts

Bash scripting provides a variety of operators that can be used to check and perform operations on files, strings, and numbers. These operators are essential for implementing conditional logic, handling user input, validating data, and managing syste...