Bash String Length

Bash String Length – In this tutorial, we will learn how to find the length of a string in Bash scripting using parameter expansion, expr length, and pattern matching with expr.

The most common and recommended Bash syntax is ${#string}. It is simple, fast, and does not start an external command. The expr examples are also useful when you are reading older shell scripts or working with basic shell utilities.

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" : '.*'

Bash string length examples with parameter expansion and expr

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

Example 1 – Bash string length using ${#str}

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

The value is 12 because Bash counts each character in Good morning, including the space between the two words.

Example 2 – Bash string length using expr length

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

Here, command substitution stores the output of expr length "$str" in the variable length. In new scripts, $(...) is usually easier to read than backticks, but the result is the same.

</>
Copy
length=$(expr length "$str")

Example 3 – Bash string length using expr pattern match

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

The expression '.*' matches the complete string, and expr returns the number of matched characters.

Recommended Bash string length method for scripts

For Bash scripts, prefer ${#str} unless you have a specific reason to use expr. It is built into Bash syntax and avoids running another process.

MethodExampleWhen to use it
Bash parameter expansion${#str}Best choice for normal Bash scripts.
expr lengthexpr length "$str"Useful in older shell examples or when working with expr already.
expr pattern matchexpr "$str" : '.*'Useful when you need length through a matching expression.

Find length of an empty string and a string with spaces in Bash

An empty string has length 0. Spaces inside a string are also counted. Leading and trailing spaces are counted too, as long as they are stored in the variable.

</>
Copy
#!/bin/bash

empty=""
message="  Bash script  "

echo "Empty string length: ${#empty}"
echo "Message length: ${#message}"

Output

Empty string length: 0
Message length: 15

The second string contains two leading spaces and two trailing spaces. Those spaces are part of the string value, so they are included in the length.

Check if a Bash string length is greater than zero

You can use ${#str} inside a numeric test when your script has to validate whether a variable has content.

</>
Copy
#!/bin/bash

username="arjun"

if [[ ${#username} -gt 0 ]]; then
  echo "Username is not empty"
else
  echo "Username is empty"
fi

Output

Username is not empty

For simple empty-string checks, [[ -n "$username" ]] is also common. Use ${#username} when you need the actual number of characters or a numeric length comparison.

Find length of each line read from a file in Bash

When reading text from a file, you can calculate the length of each line with ${#line}. The newline character at the end of each line is not included by read.

</>
Copy
#!/bin/bash

while IFS= read -r line; do
  echo "${#line}: $line"
done < names.txt

If names.txt contains the following lines:

Ravi
Meena
Suresh Kumar

The script prints:

4: Ravi
5: Meena
12: Suresh Kumar

Bash string length with arrays and command output

Be careful when using the length syntax with arrays. ${#arr[@]} returns the number of array elements, while ${#arr[0]} returns the length of the first array element.

</>
Copy
#!/bin/bash

items=("red" "green" "blue")

echo "Number of items: ${#items[@]}"
echo "Length of first item: ${#items[0]}"

Output

Number of items: 3
Length of first item: 3

You can also store command output in a variable and then find its length. Quote the command substitution when you want to preserve spaces in the value.

</>
Copy
#!/bin/bash

current_dir="$(pwd)"
echo "Current directory path length: ${#current_dir}"

Character length and byte length in Bash strings

${#str} gives the string length as Bash sees it under the current shell environment and locale. For ordinary ASCII text, the character count and byte count are the same. For non-ASCII text, they may differ depending on locale and the tool used to count bytes.

For example, use Bash parameter expansion when you want the Bash string length in your script. Use byte-counting tools only when you specifically need storage size or byte length.

</>
Copy
#!/bin/bash

str="Bash"

echo "Bash string length: ${#str}"
printf "%s" "$str" | wc -c

Output

Bash string length: 4
4

Common mistakes while finding Bash string length

  • Writing $#str instead of ${#str}. The braces are required for string length.
  • Forgetting quotes with expr length "$str" when the string contains spaces or special characters.
  • Using ${#arr[@]} expecting string length, when it actually returns the number of array elements.
  • Assuming spaces are ignored. Bash counts spaces that are part of the string value.
  • Using external commands for simple length checks when ${#str} is enough in Bash.

QA checklist for Bash string length examples

  • Confirm that the script uses ${#variable} for the primary Bash string length example.
  • Check that strings with spaces are quoted in expr examples.
  • Verify that expected output counts spaces inside the string.
  • Confirm that array examples distinguish element count from element string length.
  • Check that output-only blocks use the output class for PrismJS formatting.

FAQs on Bash string length

How do I find the length of a string in Bash?

Use ${#str}, where str is the variable name. For example, if str="Hello", then ${#str} returns 5.

Does Bash string length count spaces?

Yes. Bash counts spaces that are part of the string. For example, Good morning has length 12 because the space between the words is included.

What is the difference between ${#str} and expr length “$str”?

${#str} is Bash parameter expansion and is usually preferred in Bash scripts. expr length "$str" runs the external expr command to calculate the length.

How do I check if a Bash string is empty using length?

Use a numeric comparison such as [[ ${#str} -eq 0 ]]. This condition is true when the string length is zero.

How do I find the length of a line from a file in Bash?

Read each line into a variable and use ${#line}. For example, inside a while IFS= read -r line loop, ${#line} gives the length of the current line.

Conclusion – finding Bash string length safely

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

For most Bash scripting tasks, use ${#str} to get the string length. Use expr length "$str" or expr "$str" : '.*' when you specifically need those forms or when maintaining older shell scripts. Always quote variables in command-based examples, and remember that spaces inside the string are counted.