0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Find Length of String in Bash: Simple Guide

In Bash, you can find the length of a string using ${#string}. This syntax returns the number of characters in the variable string.
📐

Syntax

The syntax to find the length of a string in Bash is ${#string}.

  • string: The variable holding your text.
  • ${#string}: Expands to the length of the string stored in string.
bash
length=${#string}
💻

Example

This example shows how to store a string in a variable and then print its length using ${#string}.

bash
string="Hello, Bash!"
length=${#string}
echo "Length of string: $length"
Output
Length of string: 12
⚠️

Common Pitfalls

One common mistake is trying to use strlen like in other languages; Bash does not have this function. Another is forgetting to use the variable name without quotes inside the length syntax.

Wrong: length=${#"$string"} or length=strlen($string)

Right: length=${#string}

bash
string="test"
# Wrong way:
# length=${#"$string"}  # This will not work as expected
# length=strlen($string) # Bash has no strlen function

# Right way:
length=${#string}
echo "$length"
Output
4
📊

Quick Reference

OperationSyntaxDescription
Get string length${#string}Returns number of characters in string
Print lengthecho ${#string}Displays length on terminal
Assign lengthlength=${#string}Stores length in variable

Key Takeaways

Use ${#string} to get the length of a string in Bash.
Do not use functions like strlen; they do not exist in Bash.
Avoid quoting the variable inside the length syntax.
Store the length in a variable or print it directly with echo.
This method counts all characters including spaces and punctuation.