String Variables in Bash [Manipulation, Interpolation & Testing]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

String variables perform an exclusive role in Bash scripting. So, whether you are a beginner or an experienced Linux user, it doesn’t matter at all. All that matters is to understand the practical facts of string variables to automate the scripting tasks. With the ultimate flexibility of the Bash string variable, you can easily cache the sequence of characters, handle user inputs, manipulate data, and generate dynamic prompts. So, let’s move on to the article to visualize the dynamic operations regarding string variables in Bash.

Key Takeaways

  • Learning about the Bash string variables.
  • Learning about the manipulation, and interpolation of string variables in Bash.

Free Downloads

What Are Bash String Variables?

String variables refer to the types of variables that help to store, handle, and manipulate text sequences in Bash. These strings can be in letters, numbers, whitespace, or special characters form. As soon as you insert characters’ sequences into a variable, Bash assumes them as string variables you can use without declaring the data types.

Basic Notation >

  • The first character must be a letter (either A-Z or a-z) or an underscore (_).
  • The rest characters can include letters, underscores, and digits.

5 Cases for Manipulating Bash String Variables

Manipulation outlines several operations that you can perform on string variables. Here are some of the key operations for manipulating string variables in Bash:

Case 1: Assigning & Accessing String Variables in Bash

If you want to create a string variable, you need to assign a value to the variable like variable_name=”value”. And for accessing the variable you have to put a dollar sign ($) before the variable name. Following is the step-by-step procedure for assigning & accessing Bash string variables:

Steps to Follow >

➊ Open your Ubuntu Terminal.

➋ To open a script in the nano text editor, write the command below:

nano assign.sh
EXPLANATION
  • nano: A text editor.
  • assign.sh: This is a script. Here, I have named the script by ‘assign.sh’. You can name any of your choices.

Opening file in Nano editor

➌ Hereafter, write the following script inside the editor:

Script (assign.sh) >

#!/bin/bash

#Creating an empty string variable
EmptyString=""

#Assigning string variable with a single word
WordString="Hi, string!"

#Assigning string variable with multiple words
SentenceString="String variables are essential."

#Assigning string variable with special characters
Special_charString="()$!^#@&%*"

#Accessing the string variables
echo $EmptyString
echo $WordString
echo $SentenceString
echo $Special_charString
EXPLANATION

In #!/bin/bash, ‘#!’ is called ‘Shebang’ or ‘Hashbang’. The lines ‘EmptyString=””’, ‘WordString=”Hi, string!”’,’SentenceString=”String variables are essential.”’, and ‘Special_charString=”()$!^#@&%*”’ indicate four different types of variable assignment. On the contrary, ‘echo $EmptyString’, ‘echo $WordString’, ‘echo $SentenceString’, and ‘echo $Special_charString’ indicate the variable access.

➍ Then, press CTRL+S to save the file & press CTRL+X to exit.

➎ After that, use the command below to make the script executable:

chmod u+x assign.sh
EXPLANATION
  • chmod: Changes the permission of the files and directories.
  • u+x: Adds the executable permission for the user.
  • assign.sh: The file which you want to make executable.
Adding executable permission to the script➏ Finally, run the script by the following command:

./assign.sh

Output of the assigned string variablesFrom the above image, you can observe the different outputs of the assigned variables.

Case 2: Concatenating String Variables in Bash

Concatenation indicates the procedure of combining multiple variables into a single string. In Bash, you can easily concatenate string variables by putting the strings next to each other.

You can follow the steps of Case 01, to save & make the script executable.

Script (concatenate.sh) >

#!/bin/bash

firstpart="Hello, "
secondpart="Linux"
lastpart="Simply!"

fullname=$firstpart$secondpart$lastpart

echo $fullname
EXPLANATION

Here, ‘fullname=$firstpart$secondpart$lastpart’ indicates concatenating three variables firstpart’, ‘secondpart’, and ‘lastpart’ into a string $firstpart$secondpart$lastpart and then storing the string in a new variable ‘fullname’.

Now, run the script by the following command:

./concatenate.sh

Output of concatenated string variablesThe above image outlines the concatenated output of the assigned string variables.

Case 3: Calculating String Length

Using the syntax ${#variable}, you can determine a string length stored in a string variable.

You can follow the steps of Case 01, to save & make the script executable.

Script (length.sh) >

#!/bin/bash

String="Wow, LinuxSimply!"
Length=${#String}
echo $Length
EXPLANATION

The line ‘Length=${#String}’ calculates the length of the string that is stored in the variable ‘String’ using the ${#String} syntax and passes the result to the variable ‘Length’.

Now, run the script by the following command:

./length.sh

Output showing the length of the stringFrom the snapshot, you can see that the counted length of the string I assigned is 17.

Case 4: Extracting & Replacing Substring

The syntax ${variable:start:length} helps you to extract a substring from a string variable. And ${variable/search/replace} helps you to replace a substring with another string.

You can follow the steps of Case 01, to save & make the script executable.

Script (extract-replace.sh) >

#!/bin/bash

string1="Hi, Softeko!"

#Extracting a substring
substring=${string1:0:2}

string2="Welcome, LinuxSimply!"

#Replacing a substring with the extracted substring
newString2=${string2/Welcome/$substring}

echo $newString2
EXPLANATION

In ‘substring=${string1:0:2}’,  ‘${string1’ indicates the substring extraction on the variable ‘string1’, ‘0’ specifies the extraction from the beginning of the string, and ‘2’ specifies the 2 characters to be extracted from the starting.

Next, in ‘newString2=${string2/Welcome/$substring}’, ‘${string2’ indicates the global substring replacement on the variable ‘string2’, ‘Welcome’ is the substring that I want to replace, and ‘$substring’ specifies the extracted substring ‘Hi’ from the variable ‘string1’ that will replace ‘Welcome’.

Now, run the script by the following command:

./extract-replace.sh

Output of extracting & replacing substringFrom the above image, you can see that the substring ‘Hi’ is replaced with ‘Welcome’.

Case 5: Converting String Variables’ Case in Bash

You can use the syntax ${variable^^} to convert the case of a string variable to uppercase and ${variable,,} to convert the case of the variable to lowercase.

You can follow the steps of Case 01, to save & make the script executable.

Script (case-convert.sh) >

#!/bin/bash

String="Linux World"

#Converting the string to uppercase
Uppercase=${String^^}

#Converting the string to lowercase
Lowercase=${String,,}

echo $Uppercase
echo $Lowercase
EXPLANATION

Here, ‘Uppercase=${String^^}’ converts the string stored in the variable ‘String’ to uppercase, and ‘Lowercase=${String,,}’ converts the string stored in the variable ‘String’ to lowercase.

Now, run the script by the following command:

./case-convert.sh

Output showing the case conversion of the stringIn the image, you can see that I have converted the string inside the ‘Stringvariable into both uppercase and lowercase.

2 Cases for Interpolating String Variables in Bash

In Bash, String Variable Interpolation interprets the process of adding value to a variable within a string. You can perform interpolation on Bash string variables by enclosing the variable name within double quotes ‘“..”’ or curly braces ‘${..}’.

Case 1: Interpolating String Variable Using Double Quotes in Bash

You can use double quotes to easily append the value of a variable inside a string.

You can follow the steps of Case 01 of manipulating Bash string variables, to save & make the script executable.

Script (double-quote.sh) >

#!/bin/bash

variable="LinuxSimply"

echo "I work for $variable website."
EXPLANATION

In ‘echo “I work for $variable website.”’, the echo command prints the string where I have interpolated the variable ‘variable’ inside the string using ‘$variable’.

Now, run the script by the following command:

./double-quote.sh

Output of interpolation using double-quotesThe image depicts that the variable interpolation using the double quotes is successfully done.

Case 2: Interpolating String Variable Using Curly Braces in Bash

Using curly braces is also a good way of string interpolation. The following section dictates an example of string interpolation using curly braces.

You can follow the steps of Case 01 of manipulating Bash string variables, to save & make the script executable.

Script (curly-brace.sh) >

#!/bin/bash

Name="Nadiba"

echo "My name is ${Name} Rahman."
EXPLANATION

In ‘echo “My name is ${Name} Rahman.”’, the echo command prints the string where I have interpolated the variable ‘Name’ inside the string using the curly braces ‘${Name}’.

Now, run the script by the following command:

./curly-brace.sh

Output of interpolation using curly-bracesThe image depicts that the variable interpolation using the curly braces is successfully done.

6 Examples for Testing String Variables in Bash

You can append testing operations on Bash string variables. For instance, you can test variables’ content, and case insensitivity, comparing them by equality, checking substrings’ presence, etc. Here are some examples of Bash string variables testing scheme:

For the following examples, you can follow the steps of Case 01 of manipulating Bash string variables, to save & make the script executable.

Example 1: Empty String Check

You can check if a string assigned to a variable is empty. If the string is empty, it prints a message to the terminal. Here’s an example:

Script (empty.sh) >  

#!/bin/bash

string=""
if [ -z "$string" ]; then
echo "String is empty."
fi
EXPLANATION

In the statement ‘if [ -z “$string” ]; then’, the ‘-z’ operator checks if the length of the string stored in the variable ‘string’ is zero. If the string is empty, the condition becomes true, and the echo command prints “String is empty.”.

Now, run the script by the following command:

./empty.sh

Output showing the assigned string variable is emptyThe above image tells that the string I have used is empty.

Example 2: Non-Empty String Check

To check if a string that is assigned to a variable is not empty and includes contents, have a look at the following part:

Script (non-empty.sh) >  

#!/bin/bash

string="Two words"
if [ -n "$string" ]; then
echo "Non-empty string."
fi
EXPLANATION

In the statement ‘if [ -n “$string” ]; then’, the ‘-n’ operator checks if the length of the string stored in the variable ‘string’ is non-zero. If the string is non-empty, the condition becomes true, and the echo command prints “Non-empty string.“.

Now, run the script by the following command:

./non-empty.sh

Output showing the assigned string variable is non-emptyThe above image tells that the string I have used is non-empty.

Example 3: Equality Check of Two String Variables in Bash

You can easily compare two string variables and check if they are equal. Following is an example related to this:

Script (equal.sh) >

#!/bin/bash

string1="Linux"
string2="Linux"
if [ "$string1" == "$string2" ]; then
echo "Two strings are equal."
fi
EXPLANATION

The line ‘if [ “$string1” == “$string2” ]; then’ checks if the value of ‘string1’ is equal to the value of ‘string2’. Here, the ‘==’ operator does the equality test inside the ‘[ ]’ syntax. If the strings are equal, the condition becomes true, and the echo command prints “Two strings are equal.“.

Now, run the script by the following command:

./equal.sh

Output showing two strings are equalThe above image shows that the strings I have used in the two variables are equal.

Example 4: Inequality Check of String Variables

To verify if the string variables you inserted are unequal, you have to first compare their values and then take the decision. So, let’s see an example:

Script (inequal.sh) > 

#!/bin/bash

string1="Linux"
string2="Windows"
if [ "$string1" != "$string2" ]; then
echo "These strings are not equal."
fi
EXPLANATION

The line ‘if [ “$string1” != “$string2” ]; then’ checks if the value of ‘string1’ is not equal to the value of ‘string2’. Here, the ‘!=’ operator does the inequality test inside the ‘[ ]’ syntax. If the strings are not equal, the condition becomes true, and the echo command prints “These strings are not equal.“.

Now, run the script by the following command:

./inequal.sh

Output showing two unequal stringThe above image shows that the strings I have used in the two variables are not equal.

Example 5: Substring Check on String Variables in Bash

You can perform a substring checking on string variables in Bash. If the substring you want to check exists in the string, then it will print a message to the Bash terminal. Have a look at the example of a substring test:

Script (substring.sh) >

#!/bin/bash

String="LinuxSimply is a website."
if [[ "$String" == *"website"* ]]; then
echo "Found the substring in the string."
fi
EXPLANATION

In ‘if [[ “$String” == *”website”* ]]; then’, the ‘==’ operator does the substring test inside the ‘[[ .. ]]’ syntax. ‘*”website”*’ indicates the matched pattern with the variable ‘String’ where ‘*’ represents any character before or after the word ‘website’. If the word ‘website’ exists as a substring in the string, the condition becomes true.

Now, run the script by the following command:

./susbtring.sh

Output showing that the string variable contains the specific substring in bashFrom the image, you can see that the word ‘website’ exists as the substring in the string.

Example 6: Case-insensitivity Check of String Variable in Bash

You can check if the word you have used is case insensitive or not. Below is an example of case insensitivity testing:

Script (case.sh) > 

#!/bin/bash

variable="Terminal"
if [[ "$variable" == [Tt][Ee][Rr][Mm][Ii][Nn][Aa][Ll] ]]; then
echo "Terminal is case-insensitive."
fi
EXPLANATION

In ‘if [[ “$variable” == [Tt][Ee][Rr][Mm][Ii][Nn][Aa][Ll] ]]; then’, the ‘==’ operator does the test inside the ‘[[ .. ]]’ syntax. And ‘[Tt][Ee][Rr][Mm][Ii][Nn][Aa][Ll]’ indicates that the case for each character in the word ‘Terminal’ may be either ‘T’, ‘E’, ‘R’, ‘M’, ‘I’, ‘N’, ‘A’, ‘L’, or ‘t’, ‘e’, ‘r’, ‘m’, ‘i’, ‘n’, ‘a’, ‘l’. If the word ‘Terminal’ is case-insensitive, then the condition becomes true.

Now, run the script by the following command:

./case.sh

Output showing that the given string variable is case-insensitive in bashThe above image corresponds that the assigned word ‘Terminal’ is case-insensitive.

Conclusion

Studying the whole article you have got a clear idea about the context of Bash string variables. So, to sum up, use Bash string variables to perform manipulation, & interpolation, enable robust text processing proficiency, and make a dynamic script.

People Also Ask

Does Bash support arrays of strings?
Yes, Bash supports arrays of strings.

Can I compare strings in Bash?
Yes, you can compare strings in Bash using the operators such as ‘==’, ‘!=’, ‘<’, ‘>’, etc.

What is the maximum size of string variable?
The strings in a string variable can be up to 32767 characters long.

Can a string variable hold any number?
Yes, a string variable can hold letters, numbers, or any other characters.

Can I perform arithmetic operations on Bash string variables?
No, as Bash uses string variables as text data, you cannot perform arithmetic operations on these. Instead, you have to use numeric variables for this.

How to remove leading and trailing whitespaces from a string variable?
Use the syntax ‘${variable##pattern}’, and ‘${variable%%pattern}’ to remove leading and trailing whitespaces from a string variable.

Related Articles


<< Go Back to Types of Variables in Bash | Bash Variables | Bash Scripting Tutorial

Rate this post
Nadiba Rahman

Hello, This is Nadiba Rahman, currently working as a Linux Content Developer Executive at SOFTEKO. I have completed my graduation with a bachelor’s degree in Electronics & Telecommunication Engineering from Rajshahi University of Engineering & Technology (RUET).I am quite passionate about crafting. I really adore exploring and learning new things which always helps me to think transparently. And this curiosity led me to pursue knowledge about Linux. My goal is to portray Linux-based practical problems and share them with you. Read Full Bio

Leave a Comment