Bash String Examples

Bash supports various string operations. Here are some examples to get you started quickly. For detailed information, see the official Bash documentation.

String Assignment

Below are a few ways to assign a string variable.

bash$ OS=Linux

Use quotes to encapsulate strings with spaces:

bash$ OS='CentOS 4.6'

Or, use double quotes to allow for variable expansion:

bash$ DISTRO="Fedora"
bash$ OS="$DISTRO Linux"
bash$ echo $OS
Fedora Linux

String Length

Determining the length of your string is easy:

bash$ PROG="Bash"
bash$ echo ${#PROG}

You can also use expr:

bash$ expr length $PROG

Substring Extraction

Below are some examples of substring expansion in the form of ${string:position} and ${string:position:length}. String indexing starts at zero!

bash$ PROG="Bash"
bash$ echo ${PROG:0}
bash$ echo ${PROG:1}
bash$ echo ${PROG:1:2}

Testing Strings

Test if a string is of length 0

[ -z $STRING ]

Test if length of string is not zero:

[ ! -z $STRING ]
[ -n $STRING ]

Test if strings are equal.

[ $STRING1 == $STRING2 ]

Remember to use quotes if the string has spaces or escape characters (newlines).

[ "$STRING1" == "$STRING2" ]

The 'not equal; operator is !=

[ $STRING1 != $STRING2 ]