Howto use if condition to compare strings in shell scripts

undefined

In this mini post, I’ll show you how to do string comparisons using if condition in shell scripts. Sure, All systems administrators did this string comparisons at least once in the scripts they created to facilitate and automate their daily tasks. I’ll use  only the string comparison part from if condition in this mini post.

To determine if the value of a variable ($var) is empty (null):

if [ "$var" == " " ] 
then
    echo variable is null
fi

To determine if the value of a variable is not empty:

if [ "$var" != " " ] 
then
    echo variable is not null
fi

To compare the contents of a variable to a fixed string:

if [ "$var" == "value" ] 
then
    echo is the same
fi

To determine if variable’s contents are not equal to a fixed string:

if [ "$var" != "value" ] 
then
    echo not the same
fi

 

If You Appreciate What We Do Here On Mimastech, You Should Consider:

  1. Stay Connected to: Facebook | Twitter | Google+
  2. Support us via PayPal Donation
  3. Subscribe to our email newsletters.
  4. Tell other sysadmins / friends about Us - Share and Like our posts and services

We are thankful for your never ending support.

Leave a Reply

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