Using If Statements In Bash

In this post I will be showing you how to use if statements in bash. If statements are basically what they sound like, if this then that. That being said they can also be written with other conditions. Below I will show some of the examples of different if statements.

Standard IF Statement

This is just a basic if statement, if this condition is met then do this.

if [ "$var" == 'true' ]; then
  echo "Variable is set to true";
fi;

IF Statement With Else

This is also a very basic if statement, if this condition is met then do this, otherwise do that.

if [ "$var" == 'true' ]; then
  echo "Variable is set to true";
else
  echo "Variable is not set to true";
fi;

IF Statement With Elif

This is a bit more complicated but still pretty simple, if this then do that, otherwise if something else then do this.

if [ "$var" == 'true' ]; then
  echo "Variable is set to true";
elif [ "$var" == 'false' ]; then
  echo "Variable is set to false";
fi;

IF Statement With Elif And Else

This is a combination of all of the above, note how you can use the elif to check for other conditions and then use else as a fallback for any unexpected issues. This can be useful when combined with exit codes and/or creating error messages.

if [ "$var" == 'true' ]; then
  echo "Variable is set to true";
elif [ "$var" == 'false' ]; then
  echo "Variable is set to false";
else
  echo "Variable is set to unexpected value";
fi;

I hope this quick guide has helped you, please don’t forget to like/comment/share! Thanks!

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *