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

str1="Hello"

Just a variable name and assign value within double quotes

How Compare two strings

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

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

How to Check whether a string is empty or not

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

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

IFS=''
read -ra ADD<<<"$str"

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

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:0:10}"
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

Output

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.