You can follow these syntaxes to implement string functions in Bash:
- Declaring String with “declare” Command:
declare a="string value"
- Asking Input from User with “read” Command:
read variable_name
- Determining Length of String:
length="${#string_name}"
- Extracting Substring from String:
extracted_string="${original_string:start:end}"
- Concatenating Strings in Bash:
concatenated_string=${string1}${string2}
- 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"
The declare -r a="Linuxsimply"
declares a variable a. The -r
option makes the variable read-only, which means it can not be changed.
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"
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.
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
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.
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
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.
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"
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.
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
The var=${a}${b}
concatenates the value of a and b and keeps it to the third variable, var.
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
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.
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
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.
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"
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.
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
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.
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
- How to Convert a Bash String to Int? [8 Methods]
- How to Format a String in Bash? [Methods, Examples]
- How to Convert Bash String to Uppercase? [7 Methods]
- How to Convert Bash String to Lowercase? [7 Methods]
- How to Replace String in Bash? [5 Methods]
- How to Trim String in Bash? [6 Methods]
- How to Truncate String in Bash? [5 Methods]
- How to Remove Character from String in Bash? [7+ Methods]
- How to Remove First Character From Bash String? [7 Methods]
- How to Remove Last Character from Bash String [6 Methods]
- How to Generate a Random String in Bash? [8 Methods]
- How to Manipulate Bash String Array [5 Ways]
- How to Use “Here String” in Bash? [Basic to Advance]
- Encode and Decode with “base64” in Bash [6 Examples]
- How to Use “eval” Command in Bash? [8 Practical Examples]
- How to Get the First Character from Bash String? [8 Methods]
<< Go Back to String Manipulation in Bash | Bash String | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners