There are three different ways of finding string length in Bash:
${#string}
- This method is used to find the number of characters in a string.expr length "$string"
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.
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
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
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