A string is an important component in every programming language. I bash string plays a vital part as well. In this, we will see the usage of string in bash or shell script.

To Execute Don't forget to run

$ chmod +x script.sh

List of Contents 

  1. How to Declare a String.
  2. How Compare two strings.
  3. How to Check whether a string is empty or not.
  4. How to Find the length of a string.
  5. How to Split a String.
  6. How Concatenate Strings.

How to Declare a String


Just a variable name and assign value within double quotes

How Compare two strings

if [ $str1 = $str2 ]
    echo "Both the strings are equal."  
    echo "Strings are not equal."  

We can also use \< and \> as less then and grater then.

How to Check whether a string is empty or not

if [ -n $str1 ]
    echo "String is not empty"  
    echo "String is empty"  

How to Find the length of a string

# There is few methods 

1.  ${#string}  
2.  expr length "$string"  
3.  expr "$string" :'.*'  
4.  $str |awk '{print length}' 

Any one of this will find the length of a string for you.

How to Split a String

read -ra ADD<<<"$str"

for i in "${ADD[@]}";
echo "$i"

This is for split separated by space, you can use any word or single char in IFS=' #withen_This'

 Sub string of a string

substr="${str:(-5)}"#For last 5 Characters

How Concatenate Strings

There is 3 way basically

~ string1+=$string2
~ string3=$string1$string2
~ string2="$string1 World"

Let's Execute

$ ./script.sh


String 1 = Hello
String 2 = Hello
Both the strings are equal.
String is not empty
Length of 'Hello Programmers' is 17
Length of 'Hello Programmers' is 17
Length of 'Nothing is impossible' is 21
Length of 'Hello Programmers' is 17
Enter any string separated by space: I am ok
I am ok
Hello programmers Let's code.
Total characters in a String: 29
Substring: Hello prog
Total characters in Substring: 10
String using last 5 char=  you.
Hello world
Hello world
Hello World

Share with me if you have any better way of doing this.