Finding the length of a string

Finding the length of a string

How to:

The # symbol gets the job done in bash. Use it with parameter expansion. Here’s how:

my_string="Hello, World!"
echo $string_length

Sample output:


Deep Dive

In the old days, folks used expr or external tools like wc -m, but Bash built-in features changed the game. The ${#var} syntax is part of parameter expansion introduced in Bash. It’s fast and efficient because it doesn’t spawn a subshell or call an external program.

Alternatives? Sure, you got ’em:

  • expr length "$my_string" gives you the same result, but it’s kinda old-school.
  • echo -n $my_string | wc -m uses wc to count, but it’s an overkill for simple tasks.

Details, details… When you use ${#my_string}, it gets you the length in bytes by default. If your text walks on the unicode side of the street, you might need to consider multi-byte characters. That’s when things get more complex.

See Also

Dive into the man pages with man bash to get into the weeds of parameter expansion. For those looking into handling strings beyond basic ASCII, the Advanced Bash-Scripting Guide offers some insights: And for the love of learning, keep an eye on for the latest on Bash.