Working with Strings in Shell Scripting

In shell scripting, string tests are used to perform various operations and comparisons on strings. These tests allow you to check characteristics of strings, such as their length or content. Here are some commonly used string tests in shell scripting:

  1. String Length Comparison:
  • [-z string]: True if the length of string is zero (i.e., it is empty).
  • [-n string] or [string]: True if the length of string is non-zero (i.e., it is not empty).

Example:

Bash
str=""
if [ -z "$str" ]; then
   echo "String is empty"
fi

  1. String Equality and Inequality:
  • ==: Checks if two strings are equal.
  • !=: Checks if two strings are not equal.

Example:

Bash
str1="hello"
str2="world"
if [ "$str1" == "$str2" ]; then
   echo "Strings are equal"
else
   echo "Strings are not equal"
fi

  1. Substring Checks:
  • [string1 = string2]: Checks if string1 is equal to string2. (Note: This is a synonym for ==.)
  • [string1 != string2]: Checks if string1 is not equal to string2. Example:

Example:

Bash
str1="apple"
str2="apple pie"
if [ "$str1" = "$str2" ]; then
   echo "Strings are equal"
else
   echo "Strings are not equal"
fi

  1. String Length Comparison (Alternative):
  • ${#string}: Returns the length of the string. Example:

Example:

Bash
str="hello"
length=${#str}
echo "Length of string is $length"

  1. Substring Testing:
  • [string1 \< string2]: Checks if string1 is lexicographically less than string2.
  • [string1 \> string2]: Checks if string1 is lexicographically greater than string2.

Example:

Bash
str1="apple"
str2="banana"
if [ "$str1" \< "$str2" ]; then
   echo "$str1 comes before $str2"
else
   echo "$str2 comes before $str1"
fi

  1. Substring Checks:
  • [string1 =~ regex]: Checks if string1 matches the regular expression regex. Example:

Example:

Bash
str="12345"
if [[ $str =~ ^[0-9]+$ ]]; then
   echo "String contains only digits"
else
   echo "String contains non-digit characters"
fi

These string tests are crucial for conditional execution in shell scripts, allowing you to control the flow of your script based on the properties of strings. Remember to use proper quoting to handle cases where strings may contain spaces or special characters.

Share
OpenLib .

OpenLib .

The Founder - OpenLib.io

You may also like...