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:
- String Length Comparison:
[-z string]
: True if the length ofstring
is zero (i.e., it is empty).[-n string]
or[string]
: True if the length ofstring
is non-zero (i.e., it is not empty).
Example:
str=""
if [ -z "$str" ]; then
echo "String is empty"
fi
- String Equality and Inequality:
==
: Checks if two strings are equal.!=
: Checks if two strings are not equal.
Example:
str1="hello"
str2="world"
if [ "$str1" == "$str2" ]; then
echo "Strings are equal"
else
echo "Strings are not equal"
fi
- Substring Checks:
[string1 = string2]
: Checks ifstring1
is equal tostring2
. (Note: This is a synonym for==
.)[string1 != string2]
: Checks ifstring1
is not equal tostring2
. Example:
Example:
str1="apple"
str2="apple pie"
if [ "$str1" = "$str2" ]; then
echo "Strings are equal"
else
echo "Strings are not equal"
fi
- String Length Comparison (Alternative):
${#string}
: Returns the length of the string. Example:
Example:
str="hello"
length=${#str}
echo "Length of string is $length"
- Substring Testing:
[string1 \< string2]
: Checks ifstring1
is lexicographically less thanstring2
.[string1 \> string2]
: Checks ifstring1
is lexicographically greater thanstring2
.
Example:
str1="apple"
str2="banana"
if [ "$str1" \< "$str2" ]; then
echo "$str1 comes before $str2"
else
echo "$str2 comes before $str1"
fi
- Substring Checks:
[string1 =~ regex]
: Checks ifstring1
matches the regular expressionregex
. Example:
Example:
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.