Bash String Length

Bash String Length – In this tutorial, we will learn ways to find the length of a string in Bash Scripting.

To find String Length in Bash Scripting use one of the following syntax.

Syntax 1

</>
Copy
${#string}

Syntax 2

</>
Copy
expr length "$string"

Observe the double quotes around $string . If your string has spaces, double quotes around $string is kind of mandatory, else in other cases you may ignore. However, to be on the safe side, always try including double quotes around $string.

Syntax 3

</>
Copy
expr "$string" : '.*'

Examples

In the following examples, we will go through different processes to find the string length in bash shell scripting.

Example 1 – Bash String Length

In the following example, we use ${#string_variable_name} to find string length.

Bash Script File

</>
Copy
#!/bin/bash

str="Good morning"
length=${#str}
echo "Length of '$str' is $length"

Run the above program in Terminal, and you shall get the following output.

Output

$ ./bash-string-length-example 
Length of 'Good morning' is 12

Example 2

In this example, we use expr length "$str" to find string length.

Bash Script File

</>
Copy
#!/bin/bash

str="Bash Shell Scripting Tutorial"
length=`expr length "$str"` 
echo "Length of '$str' is $length"

Run the above program in Terminal, and you shall get the following output.

Output

$ ./bash-string-length-example 
Length of 'Bash Shell Scripting Tutorial' is 29

Example 3

In this example, we use `expr "$str" : '.*'`  where, str is a string variable, to get the length of a string.

Bash Script File

</>
Copy
#!/bin/bash

str="Bash Shell Scripting Tutorial"
length=`expr "$str" : '.*'` 
echo "Length of '$str' is $length"

Run the above program in Terminal, and you will get the following output.

Output

$ ./bash-string-length-example 
Length of 'Bash Shell Scripting Tutorial' is 29

Conclusion

In this Bash Tutorial, we learned to find Bash String Length in different ways with the help of example Bash Shell Scrips.