Shell Programming - String Operators

Unix

Share

In this tutorial we will learn about String Operators in Shell Programming.

We will be using if else statement in this tutorial.

Equal =

We use the = equal operator to check if two strings are equal.

In the following example we will check if entered strings are equal.

#!/bin/sh

# take two strings from user
echo "Enter first string:"
read str1

echo "Enter second string:"
read str2

# check
if [ "$str1" = "$str2" ]
then
  echo "Strings are equal."
else
  echo "Strings are not equal."
fi

Output:

$ sh equal.sh 
Enter first string:
Hello
Enter second string:
hello
Strings are not equal.

$ sh equal.sh 
Enter first string:
Hello
Enter second string:
Hello
Strings are equal.

Note! We are enclosing str1 and str2 in double quotes like [ "$str1" = "$str2" ] to handle multi-word strings.

Not equal !=

We use the != not equal operator to check if two strings are not equal.

In the following example we will check if entered string is not equal to "Hello World".

#!/bin/sh

# take a string from user
echo "Enter string:"
read str

s="Hello World"

# check
if [ "$str" != "$s" ]
then
  echo "$str not equal to $s."
else
  echo "$str equal to $s."
fi

Output:

$ sh notequal.sh 
Enter string:
Hello
Hello not equal to Hello World.

$ sh notequal.sh 
Enter string:
Hello World
Hello World equal to Hello World.

-z to check size zero

We use -z to check if the size of the string is zero.

In the following example we will check if the size of the entered string is zero.

#!/bin/sh

# take a string from user
echo "Enter string:"
read str

# check
if [ -z "$str" ]
then
  echo "String size equal to 0."
else
  echo "String size not equal to 0."
fi

Output:

$ sh zerosize.sh 
Enter string:
Hello World
String size equal to 0.

$ sh zerosize.sh 
Enter string:

String size equal to 0.

-n to check size not zero

We use -n to check if the size of the string is not zero.

In the following example we will check if the size of the entered string is not zero.

#!/bin/sh

# take a string from user
echo "Enter string:"
read str

# check
if [ -n "$str" ]
then
  echo "String size not equal to 0."
else
  echo "String size equal to 0."
fi

Output:

$ sh notzerosize.sh 
Enter string:
Hello
String size not equal to 0.

$ sh notzerosize.sh 
Enter string:

String size equal to 0.

${#str} to find length of the string

In the following example we will print the length of the entered string.

#!/bin/sh

# take a string from user
echo "Enter string:"
read str

echo "Length of the entered string = ${#str}"

Output:

$ sh length.sh 
Enter string:

Length of the entered string = 0


$ sh length.sh 
Enter string:
Hello
Length of the entered string = 5


$ sh length.sh 
Enter string:
Hello World
Length of the entered string = 11
Share

Recently Updated