String comparison with Bash

 

In this article I will explain bash specific string comparison.

Here my input string is “abcdef” and defined it as following:

S="abcdef"

To check if a string startswith:

if [[ "$S" == abc* ]]
then
 echo true
else
 echo false
fi

Output:

true

To check if a string endswith:

if [[ "$S" == *def ]]
then
 echo true
else
 echo false
fi

Output:

true

To check if a string contains:

if [[ "$S" == *cd* ]]
then
 echo true
else
 echo false
fi

Output:

true

After writing any of the above comparison in a script you need to run it with bash only.

Lets say if we are written any of the above code in test.sh script, run it with following command:

$ bash test.sh

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s