← Back to Bash Course | Chapter 5: Functions | Lesson 1 of 11

String Length

String length is like counting the letters on a name tag. Bash can tell you how many characters are in your text with one short trick.

In this page:

  1. String Length
Syntax
bash
${#variable_name}

String Length

${#variable} gives the number of characters in a string variable. It's a fast, built-in way to check string length without calling an external command like wc. This syntax is part of Bash's parameter expansion feature.

Note: Use ${#var} instead of piping through wc -c — it avoids starting a subprocess.

Example: String Length

bash
#!/bin/bash
name="Hello, Bash!"
echo "Length: ${#name}"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using ${#var} on an array and getting the length of the first element instead of the number of items.
  2. Forgetting the #, as in ${var}, which just gives the value.
  3. Expecting ${#var} to count bytes, when it counts characters in a UTF-8 locale.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.