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:
Syntax
${#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
#!/bin/bash
name="Hello, Bash!"
echo "Length: ${#name}"
Login to try C/C++/Java/PHP code in the editor
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
- Using
${#var}on an array and getting the length of the first element instead of the number of items. - Forgetting the
#, as in${var}, which just gives the value. - Expecting
${#var}to count bytes, when it counts characters in a UTF-8 locale.
🔒
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: