BASH Programming

How to Work with Strings in Bash

The string data is used for various purposes in programming. Since Bash is a weakly typed language, no data type declaration is required to declare the string variables in Bash. The string data can be manipulated by Bash script in different ways. Different types of tasks that are commonly required to do with the string values for solving the Bash programming problems are shown in this tutorial using multiple Bash scripts.

List of Contents:

  1. Declare and Print the String
  2. Find Out the Length of the String
  3. Change the Case of the String
  4. Concatenate the String Values
  5. Compare the String Values
  6. Print the String Values with Formatting
  7. Search and Replace the String Values Using Regex
  8. Extract the Substring from the String
  9. Delete a Substring from a String
  10. Substitute the String with the “Sed” Command

Declare and Print the String

The following script shows the method of assigning the string value to a variable and print the value of the variable in the output. A default string value is assigned in the first string variable and a string value is taken from the user after executing the script.

#!/bin/bash

#Assign a string value to a variable
str1="Bash"
#Read string data from the user
read -p "Enter a string value: " str2

#Print the string values
echo "The first string value is $str1"
echo "The second string value is $str2"

Output:

The following output appears after executing the script. The values of both string values are printed here:

Go to top

Find Out the Length of the String

The length of the string can be counted in different ways using the Bash script. The most common method of counting the string length is using the parameter expansion. The “expr” and “awk” commands can be used to count the length of a string. The uses of three options to count the length of a string are shown in the following script:

#!/bin/bash

#Take string value
echo -n "Enter your name: "
read name

#Count the length of a string  by using the hash
echo "The name contains ${#name} characters."

#Count the length value by using `expr`
len1=`expr length $name`
printf "The name contains %s characters.\n" $len1

#Count the length value by using `awk`
len2=`echo $name |awk '{print length}'`
printf "The name contains %s characters.\n" $len2

Output:

The following output appears after executing the script. The same output is generated by the three options that are shown in the script to count the length of a string:

Go to top

Change the Case of the String

The double caret symbols (‘^^’ ) are used to convert the string value into uppercase and the double commas (,,) are used to convert the string into lowercase. The method of converting the string into uppercase and lowercase is shown in the following script:

#!/bin/bash

#Take a string value from the user
read -p "Enter a string value: " str

#Print the original string value
echo "The original string value: $str"
#Print the string value in uppercase
echo "The string value in uppercase: " ${str^^}
#Print the string value in lowercase
echo "The string value in lowercase: " ${str,,}

Output:

The following output appears after executing the script for the input value of “Bash Scripting Language”:

p3

Go to top

Concatenate the String Values

Multiple ways exist in Bash to concatenate the string values. Two ways of concatenating the string values in Bash are shown in the following script. One way is just combining the string values and another way is using the “+=” operator.

#!/bin/bash
#Define a string variable
str1="LinuxHint"
#Concatenate string with another string value
combineStr="Welcome to $str1."
#Print the concatenated string
echo $combineStr

#Define another string value
str2="Bash "
#Concatenate string by using '+' operator
str2+="Script."
#Print the concatenated string
echo $str2

Output:

The following output appears after executing the script:

Go to top

Compare the String Values

The method of checking whether two string values are equivalent or not is shown in the following script. The equivalent operator (==) is used to check the equivalency of two string values. The first equivalent operator is used in the script to check whether the variables contain the empty string or not. The second equivalent operator is used to check whether two string values that are taken from the user are equivalent or not.

#!/bin/bash

#Take the string values
read -p "Enter the first string: " str1
read -p "Enter the second string: " str2

#Check whether the string values are empty or not empty
if [[ $str1 == "" || $str2 == "" ]]
then
     echo "One or more input values are empty"
else

        #Check equality of two string variables
        if [ $str1 == $str2 ]; then
               echo "Both input strings are equal."
        else
               echo "Input strings are not equal."
        fi
fi

Output:

The following output appears after executing the script for the input values of “bash” and “python”. Here, the input values are not equivalent:

The following output appears after executing the script for the input values of “bash” and “bash”. Here, the input values are equivalent:

The following output appears after executing the script for the empty input values. Here, the input values are empty:

Go to top

Print the String Values with Formatting

The “printf” command is used to print the formatted output of the string in Bash. In the following script, a string value is taken from the user, and the “printf” command is used to print the formatted output of the input value. Here, the “if” statement is used to check whether the input value is empty or not before printing the output.

#!/bin/bash

#Take a string value
read -p "Enter your favorite programming language: " lang

if [ ! -z $lang ]
then
     #Print the formatted output
     printf "Your favorite programming language is %s\n" "$lang"
else
     #Print the error message
     echo "No input value is given."
fi

The following output appears after executing the script for the input value of “PHP”:

The following output appears after executing the script for the empty input value:

Go to top

Search and Replace the String Values Using Regex

Many ways exist in Bash to search and replace the part of a string value. The regex pattern is one of the ways to search and replace the part of a string value in Bash. In the following script, a string value is taken from the user and the word “programming” is searched in the input string. If the input value contains the search word, the word of the input value is replaced by the word “scripting” and the replaced string value is stored into another variable. Then, both the original and the modified string values are printed in the output.

#!/bin/bash

#Take the main string value
read -p "Enter a string value: " Str

#Replace string by using regex pattern
replaceStr="${Str/programming/scripting}"

#Print the main string and the replaced string
echo "The main string value is $Str"
echo "The replaced string value is $replaceStr"

The following output appears after executing the script with the input value of “Bash programming language”. The word “programming” exists in the input value. So, the modified string is “Bash scripting language” which is printed in the output:

Go to top

Extract the Substring from the String

Bash has no built-in function to get a substring from a string value like other programming languages. But multiple options exist in Bash to do the same task. Two ways are shown in the following script to get the substring from a string value that is taken from the user. One way is to use the parameter expansion and another way is to use the “expr” command with the “substr”.

#!/bin/bash

#Take the main string value
read -p "Enter a string value: " Str

if [ ! -z $Str ]
then

    #Use of parameter expansion
    echo "The substring by using parameter expansion: "
    echo ${Str:5:4}

    #Use of 'substr' and `expr` command
    echo "The substring by using 'substr' with 'expr' command: "
    expr substr "$Str" 6 4
fi

Output:

The following output appears after executing the script with the input value of “LinuxHint”. In the parameter expansion, the starting position is 5 which starts counting from 0 and the substring length is 4. So, the “Hint” string is printed for the parameter expansion. In the “expr” command, the starting position is 6 which starts counting from 1 and the substring length is 4. The output of this command is the same as the parameter expansion:

Go to top

Delete a Substring from a String

The “delete” substring from a string value is another way of getting a substring like the previous example. The “cut” command can be used to cut or delete a part of a string value that is shown in the following script. According to the script, an input value is taken from the user and checked whether the input value is empty or not. If the input value is non-empty, the “cut” command cuts a particular portion of the input value and stores it into a variable. Then, the original string value and the deleted string value are printed later.

#!/bin/bash

#Take the main string value
read -p "Enter a string value: " Str

if [ ! -z "$Str" ]
then

   #Delete a particular part of the main string
   mStr=$(echo "$Str" | cut -c 7-11)

   #Print the main string and the string after deleting
   echo "The main string value is $Str"
   echo "The string value after deleting substring is $mStr"
fi

Output:

The following output appears after executing the script with the input value of “Hello World”. The starting position is set to 7 and the ending position is set to 11 in the “cut” command. So, the “cut” command returns the “World” that is printed in the output:

Go to top

Substitute the String Value in a File with the “Sed” Command

The “sed” command can be used for multiple purposes in the Bash script. The string value in a file can be substituted using this command. Create a text file with the following content that will be used to show the use of the “sed” command to search and replace the particular string value from the file.

temp.txt

I like Bash Programming.

Bash is an interpreted language.

Bash is a weakly typed language.

In the following script, the filename is taken from the user. If the filename exists in the current location, the original content of the file is printed using the “while” loop before substituting the content of the file. The search word and the replace word are taken from the user. If both input values are non-empty, the “sed” command is used to search and replace the content of the file based on the input values. The content of the file is printed again after the modification.

#!/bin/bash

#Take the filename
read -p "Enter the filename: " fn

if [ -f $fn ]
then
       echo "The original content of the file:"
       while read -r ln; do
          echo "$ln"
       done <$fn

       echo

       #Take the search string value
       read -p "Enter the search word: " searchStr

       #Take the replace string value
       read -p "Enter the replace word: " replaceStr

       #Check whether the search and replace string values are empty or not
       if [[ ! -z $searchStr && ! -z $replaceStr ]]
       then
              sed -i "s/$searchStr/$replaceStr/" $fn
       fi

       echo

       echo "The modified content of the file:"
       while read -r ln; do
          echo "$ln"
       done <$fn
else
      echo "No filename is given."
fi

Output:

The following output appears after executing the script with the “temp.txt” filename, the search word “Python”, and the replace word “Bash”. According to the output, the word “Python” exists in the “temp.txt” file three times and these words are replaced by the word “Bash” in the file:

Go to top

Conclusion

The uses of string data in Bash are shown in this tutorial using 10 different Bash script examples. Most of the basic uses of the string data in Bash are covered in this tutorial to help the new Bash users.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.