How to find string length in Bash Shell?

There are three different ways of finding string length in Bash:

  1. Using ${#string}- This method is used to find the number of characters in a string.
  2. Using expr length "$string"
  3. Using expr "$string" : ".*"- Make sure there is a space before and after colon(:) otherwise it will concatenate both of them.

Note: You have to use backquote(`) to store the output of expr command in a variable.

String length using ${#string}

mystring="Learn Bash Shell Scripting"
len=${#mystring}
echo "Length of '$mystring' is $len"

Output of the above program-

Length of 'Learn Bash Shell Scripting' is 26

String length using expr length "$string"

mystring="I am learning Bash Shell"
len=`expr length "$mystring"`
echo "Length of '$mystring' is $len"

Output of the above program-

Length of 'I am learning Bash Shell' is 24

String length using expr "$string" : ".*"

mystring="Bash Shell Scripting is amazing"
len=`expr "$mystring" : ".*"`
echo "Length of '$mystring' is $len"

Output of the above program-

Length of 'Bash Shell Scripting is amazing' is 31

Recommended Posts