How to Use String Functions in Bash? [Examples Included]

You can follow these syntaxes to implement string functions in Bash:

  1. Declaring String with “declare” Command: declare a="string value"
  2. Asking Input from User with “read” Command: read variable_name
  3. Determining Length of String: length="${#string_name}"
  4. Extracting Substring from String: extracted_string="${original_string:start:end}"
  5. Concatenating Strings in Bash: concatenated_string=${string1}${string2}
  6. Splitting Strings Into Arrays in Bash: read -a array_name <<< "$string_name"

Before using, a string variable must be declared properly, and then the string can be assigned to the declared string variable either manually or from user input. There are string functions in Bash for determining the length of a string, concatenating multiple strings into a single string, and splitting strings into arrays and individual words according to the specified Internal Field Separator(IFS). In this article, I will briefly discuss these.

1. Declaring String with “declare” Command

The declare command declares a variable. The syntax for declaring a variable and assigning a value to that variable is: declare option variable_name=value. Here is a bash script for this:

#!/bin/bash

declare -r a="Linuxsimply"
echo "$a"
EXPLANATION

The declare -r a="Linuxsimply" declares a variable a. The -r option makes the variable read-only, which means it can not be changed.

A string variable is declared using string function in bash then printed.

2. Asking Input from User with “read” Command

A value can be assigned to a variable by taking input from the user with the read command. The read command reads input from the user using the syntax: read variable_name. Here is a bash script:

#!/bin/bash

read -p 'Enter your name: ' a
echo "Hello $a"
EXPLANATION

The read -p 'Enter your name: ' a takes input from the user and keeps it to the variable a. The -p option to display ‘Enter your name: ‘ in the prompt.

Input taken from user.

3. Determining Length of String

The string contains various types of characters. To determine a string’s length, put ‘#’ before the string variable name. The syntax is length="${#variable_name}". It will return the length of the string contained in variable_name. Here is a bash script:

#!/bin/bash

a="Linuxsimply"
l="${#a}"
echo $l
EXPLANATION

The l="${#a}" calculates the length stored in the variable a and keeps it to the l variable. And the echo command prints the value of l.

Length of string is determined using string function in Bash.

4. Extracting Substring from String

Parameter expansion can extract a specific substring from a string. Use the syntax substring="${string:start:end}" to extract a substring from the original string. Here is the bash script to do so:

#!/bin/bash

a="LinuxSimply"
b=”${a::5}”
echo $b
EXPLANATION

The b="${a::5}" extracts a substring from the string stored in the variable ‘a’. Here, the a::5 specifies extracting from the beginning to the 5th character.

A substring is extracted from original string.

5. Removing Matched Substring from Original String

Parameter expansion can remove substring from a string. To remove a dot and a substring from the end of a string, use the syntax: new_string="${original_string%.*}". Here is a complete bash script:

#!/bin/bash

declare -r a="linux.simply.sh"
echo "original string: $a"
b="${a%.*}"
echo "manipulated string: $b"
EXPLANATION

The b="${a%.*}" removes the shortest match of ‘.*’, which stands for any characters followed by a dot from the ending of the string a and keeps the remaining part of the string to the b variable.

Part of the original string is removed.

6. Concatenating Strings In Bash

In Bash, concatenation means listing strings one after another. To do so, follow the syntax: concatenated_string=${string_1} ${string_2}. Here is the complete bash script:

#!/bin/bash

a=Linux
b=Simply
var=${a}${b}
echo $var
EXPLANATION

The var=${a}${b} concatenates the value of a and b and keeps it to the third variable, var.

Two strings are concatenated.

7. Splitting String Based on Space

The string contains several words separated by space. Set space as the Internal Field Separator(IFS) to split a string based on space. Here is the complete bash script:

#!/bin/bash

a="Welcome to Linuxsimply"
IFS=' '
read -a b <<< "$a"
echo "There are ${#b[*]} words in the text."
for c in "${b[@]}";
do
  printf "$c\n"
done
EXPLANATION

The IFS=' ' sets the Internal Field Separator(IFS) variable to a space character. It is used by the read command to separate the words inside the string. The read -a b <<< "$a" reads the content of variable ‘a’ and splits it into an array ‘b’ using the space character specified in IFS. Finally, for loop iterates through each element of the array b and prints them in a newline.

The string is splitted based on space.

8. Splitting Strings Into Arrays in Bash

The string stores words separated by space. To split a string into an array in Bash, use the syntax: read -a array_name <<< "$string_name". Here, it will read string, then split it into fields and store them in an array. Below is a complete bash script:

#!/bin/bash

a='Linux Simply'
read -a b <<< "$a"
for c in "${b[@]}";
do
  printf "$c\n"
done
EXPLANATION

read -a b <<< "$a" reads the content of variable a and splits each word using the default value of the Internal Field Separator(IFS), which is whitespace including space, tab, and -a tells the read command to store it into an array ‘b’. Then, it prints every element in a new line.

The string has been splitted into an array utilizing string function in Bash.

9. Returning a String from Bash Functions Using Global Variable

A global variable is a variable that exists inside and outside of a function. A bash function can print a string using a global variable. This output can be captured after calling the function; the global variable value will be according to the function definition. Here is a complete bash script:

#!/bin/bash

function FF()
{
  returnval='Linux Simply'
}
returnval='SOFTEKO'
echo "Before: $returnval"
FF
echo "After: $returnval"
EXPLANATION

The function FF() defines a function named FF. returnval='SOFTEKO' assigns a string to returnval variable. Inside the function, returnval is assigned with a string. Then, another string is assigned to returnval at the outside of the function. And echo "Before: $returnval" prints the value of variable returnval before executing the FF function. After that, FF calls the function. Finally, echo "After: $returnval" prints the value of variable returnval after calling the function FF. Here, returnval is the global variable.

String returned from function.

10. Returning a String from Bash Functions Using Local Variable

Inside a function, a local variable can be defined with a value, and the variable’s value can be captured using command substitution. Here is an example of returning a string from bash functions using a local variable:

#!/bin/bash

function FF2()
{
  local  returnval='Hello from LinuxSimply'
  echo "$returnval"
}
val=$(FF2)
echo $val
EXPLANATION

Inside the FF2 variable, a string is assigned to the local variable returnval, and the value of returnval is printed. The val=$(FF2) calls the function and keeps the return string from the function to the val variable.

String value returned from function.

Conclusion

In conclusion, string manipulation allows users to update and edit strings according to necessity. There are many types of string functions that are discussed in this article. It will guide the learner in implementing these functions to achieve the intended task.

People Also Ask

Can Bash functions return strings?

Bash functions can not return strings directly. At first, use the echo command to print a string and capture the output when the function is called.

What is the position of a string in Bash?

The bash strings are zero-indexed. The position of the first character is ‘0’, that of the second character is ‘1’, and so on.

How to connect strings in Bash?

To connect or concatenate multiple strings into a string, place them one after another. If a="Good " b="Morning" then greeting="$a$b" concatenates the strings a and b and keeps them to the variable greeting.

How to split a string based on string Bash?

To split a string into an array in Bash, use the syntax: read -a array_name <<< "$string_name". It will split the words inside the string, and the -a option will enable it to store the words inside the array_name array.

How to find and replace string Bash?

To find and replace a string in bash, use the syntax: echo 'Original String' | sed 's/old_word/new_word'. Here, the original string will be piped to the sed command, where the ‘s’ option stands for substituting the old_word with the new_word.

Related Articles


<< Go Back to String Manipulation in Bash | Bash String | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Susmit Das Gupta

Hello everyone. I am Susmit Das Gupta, currently working as a Linux Content Developer Executive at SOFTEKO. I am a Mechanical Engineering graduate from Bangladesh University of Engineering and Technology. Besides my routine works, I find interest in going through new things, exploring new places, and capturing landscapes. Read Full Bio

Leave a Comment