Getting Started with If-Else and Exit Status

Isha JainIsha Jain
2 min read

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!!

0
Subscribe to my newsletter

Read articles from Isha Jain directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Isha Jain
Isha Jain

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