FUNDAMENTALS A Complete Guide for Beginners
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:
➊ Open your Ubuntu Terminal.
➋ To open a script in the nano text editor, write the command below:
nano assign.sh
- 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.
➌ 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
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
- 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.
./assign.sh
From 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.
Script (concatenate.sh) >
#!/bin/bash
firstpart="Hello, "
secondpart="Linux"
lastpart="Simply!"
fullname=$firstpart$secondpart$lastpart
echo $fullname
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
The 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.
Script (length.sh) >
#!/bin/bash
String="Wow, LinuxSimply!"
Length=${#String}
echo $Length
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
From 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.
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
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
From 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.
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
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
In the image, you can see that I have converted the string inside the ‘String’ variable 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.
Script (double-quote.sh) >
#!/bin/bash
variable="LinuxSimply"
echo "I work for $variable website."
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
The 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.
Script (curly-brace.sh) >
#!/bin/bash
Name="Nadiba"
echo "My name is ${Name} Rahman."
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
The 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:
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
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
The 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
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
The 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
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
The 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
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
The 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
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
From 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
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
The 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
Related Articles
- What Are Built-in Variables in Bash [2 Cases With Examples]
- An Ultimate Guide of Using Bash Environment Variables
- The “.bashrc” Environment Variables [4 Cases]
- What is Variable Array in Bash? [4 Cases]
- An Extensive Exploration of Bash Special Variables [9 Examples]
- What is Boolean Variable in Bash? [3 Cases With Examples]
- What is HereDoc Variable in Bash? [5 Practical Cases]
- What is PS1 Variable in Bash? [3 Customization Examples]
- What is PS3 Variable in Bash? [3 Practical Examples]
<< Go Back to Types of Variables in Bash | Bash Variables | Bash Scripting Tutorial