FUNDAMENTALS A Complete Guide for Beginners
Bash string operations refer to the handling of strings in a Bash script or shell environment. The string operations mainly indicate the operations that are done on the string but do not change or edit the string. Let’s see some of the basic string operations.
Length of a String
The length of a bash string refers to the number of characters in a sequence. Measuring length is important for data validation, text processing, and array indexing. Let’s see some of the methods to measure the length of a string below:
Using Parameter Expansion
The parameter expansion is the process of manipulating the values of a variable. The basic syntax is ${variable}
. Parameter expansion with hash (#) is used to measure the length of a string.
To know the length of a string, go through the following code:
#!/bin/bash
String="This is the new string. The length of the string has been calculated."
length="${#String}"
echo "The length of the string is: $length"
The string has been declared in a variable named string. Then the length is stored in the length variable. The#
in the${#String}
calculates the length of the following string variable.
From the output, you can see, that I have used the parameter expansion to count the length. You can rename the file name length.sh according to your preference.
Using “wc” Command
The wc command is a command line utility that is used for measuring the number of lines, words, and characters. This command line utility can also be used to measure the length of a string.
To find the length of a string using thewc
command, follow the script below:
#!/bin/bash
string="The string contains spaces which are counted as characters."
length=$(echo -n $string | wc -m)
echo "The length of the string is $length"
The string is declared in a variable named string with a double quote. In thelength=$(echo -n $string | wc -m)
, the-n
option with theecho
command prints the string without a newline character. The echo command output has been piped to the wc command using the pipe(|) operator. Thewc
command with the-m
option counts the character of the output of theecho
command. At last, the echo command is used to print the length of the string.
Using “awk” Command
The awk command can measure string length using the print action and length function. Here’s a bash script to find the length of the string using theawk
command:
#!/bin/bash
my_string="This is a sample string."
echo $my_string | awk '{print length}'
The output of theecho $my_string
command is piped to theawk
command. Here theprint length
is the action that will be performed on the string. The awk command calculates the length using the built-in length operator and prints the output to the terminal.
From the output, you can see the length can be measured using the “awk” command.
Concatenation of String
String concatenation refers to combining two or more strings into a single string. Concatenation is important for constructing file_path and generating dynamic command and output. This is a basic operation when using strings in scripting or programming. Some ways to concatenate strings in Bash are:
Using “+=” Operator
The “+=” operator is used for concatenation in bash. It appends the new string with the existing string.
To concatenate two strings using the<strong>+=</strong>
operator copy the following code:
#!/bin/bash
echo "Using Simple Concatenation"
string="Hello"
string+="World"
concatenated_string="$string"
echo "Concatenated String:$concatenated_string"
Here, the new string “World” is concatenated after the “Hello” using the+=
operator. Without changing the existing string, the operator mainly appended the new string to the right of the existing string.
I have renamed the script as con1.sh. You can replace the script name according to your preference.
Using the Parameter Expansion
To concatenate two or more strings you can place the string one after another using the basic syntax of the parameter expansion. Here’s how:
#!/bin/bash
echo "Using expansion"
string1="The first string."
string2="This is a new string."
concatenated_string=${string1}${string2}
echo "Concatenated String:$concatenated_string"
Two strings are assigned to the string1 and string2 variables. The${string1}${string2}
concatenates two strings by placing the strings side by side.
From the output, you can see the string is appended to the right of the first string.
Note: You can add space between ${string1} and ${string2} to add space in the final string. Also, you can concatenate multiple strings.
Appending String to a Variable
To concatenate a variable with a string use the following code:
#!/bin/bash
String1="Hello, "
String2="${String1}World"
echo "$String2"
The first string is assigned to the string1 variable. The${String1}
is the variable expansion. The string “World” is concatenated with the value of string1.
You can replace the variable with numbers or special characters.
String Comparison
String comparison is the process of evaluating relationships like equality, less/ greater than between two strings. The comparison is case-sensitive in bash scripting. Let’s see some ways of the comparison between two strings:
Find Whether Two Strings Are Equal or Not
To check whether two strings are equal or not, use the following code:
#!/bin/bash
string1="The string is"
string2="Not same."
if [ "$string1" = "$string2" ]; then
echo "Strings are equal."
else
echo "Strings are not equal."
fi
Note: Make sure to insert spaces between the single square brackets [] and a semicolon at the end of the bracket.
In the if statement, the [….] is used which is equivalent to the test command. In the [….], the=
operator is used to compare two strings. If it is true then it shows the result of the if statement; otherwise, it shows the result of the else statement.
Note: To find whether two strings are unequal, use the != operator instead of the == or = . Here within the test command, you can use the assignment operator =.
Using “>” Operator to Compare Two Strings
To compare two strings lexicographically, use the “>” operator (conditional statement ). It only uses the string’s first character to compare its ASCII value and declare which is greater than the other. Use the following code to check which one is greater between the two strings:
#!/bin/bash
string1="apple"
string2="banana"
if [[ "$string1" > "$string2" ]]; then
echo "$string1 is greater than $string2"
else
echo "$string1 is not greater than $string2"
fi
In the if statement[[ ]]
is used for lexicographical comparison. In the double bracket, the>
operator is used to test if the value of “string1” is lexicographically greater than the value of “string2”. If the statement is true, the if block will be executed. If the statement is false then the else block will be executed.
It will show that string1 is not greater than string2 because the ASCII value of “a” is less than “b”. This is case-sensitive. If you use Apple as “string1” and banana as “string2” then it will also show that string1 is not greater than string2 because the ASCII value of “A” (65) is less than “b” (98).
Conclusion
In this article, the basic operations include the string length, comparison, and concatenation which will not change the exact string. There might be some other operations that will not change the string but show some awesome results in string handling.
People Also Ask
How would you use regular expressions in a Bash script?
For pattern matching and string manipulation, you can use the regular expression. Within the test constructs[[]]
, the regular expression can be implemented using the=~
operator for conditional expressions. Here is how looks:
#!/bin/bash
str="This is a string with numbers 123"
if [[ $str =~ [0-9]+ ]]
then
echo "Contains numbers"
fi
You can also use quantifiers and anchors.
How can you execute multiple commands in one line in a Bash script?
Use a semicolon (;), the logical AND operator (&&), and the OR operator (||) in between the commands to execute multiple commands. Here is how the syntax looks:
command1 && command2
command1 || command2
command1 ; command2
What is the difference between “=” and “==” operators in comparison to two strings?
The=
indicates the assignment of a string to another one generally. The==
operator is used to compare two strings or show equality between the two strings. With a square bracket[]
, you can use the = operator and the == operator to compare between strings.
How to find the length of an array?
To find the length of an array use the parameter expansion syntax ${#arraystring[@]}. In the array, each element corresponds to one string. The syntax will find the number of strings in the array.
Related Articles
<< Go Back to Bash String | Bash Scripting Tutorial