Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Using If Statements In Bash

In this post I will show you how to use if statements in bash, you can do this directly in the prompt or in actual bash scripts. If statements basically run a command or part of your script if the condition is met.

You can check for conditions such as if a file or variable exists, if a variable is Equal to, less than or greater than, and more. Below are a few quick examples of basic if statements.

yes='1';
if [ "$yes" == '1' ]; then
echo "Yes equals 1";
fi;
if (grep -qi error /var/log/messages); then
echo "Found search string in messages file";
fi;

You can also add another piece to the puzzle called else that will basically run a different command or part of your script if that condition isn’t met. Here is a quick example below.

yes='2';
if [ "$yes" == '1' ]; then
echo "Yes equals 1";
else
echo "Yes does not equal 1";
fi;

Finally you can also add conditions to else by using elif instead, here is a simple example of using an elif in an if statement.

yes='2';
if [ "$yes" == '1' ]; then
echo "Yes equals 1";
elif [ "$yes" == '2' ]; then
echo "Yes equals 2";
else
echo "Yes does not equal 1 or 2";
fi;

I hope this quick and to the point guide has helped you learn how to use if statements, there is much more you can still do such as checking if a variable is set or if a file exists, etc. This was meant more to show you how to use an if statement in bash.

Thanks for reading and please don’t forget to like/share/comment!



This post first appeared on Teach Me Linux, please read the originial post: here

Share the post

Using If Statements In Bash

×

Subscribe to Teach Me Linux

Get updates delivered right to your inbox!

Thank you for your subscription

×