Getting string length

The "${#myvar}" form can be used to expand to the length of a string:

bash$ alpha='abcdefghijk'
bash$ printf '%u\n' "${#alpha}"
11

While this form is Bash-specific, it's a short and convenient alternative to counting characters with wc. Note that it counts characters according to your locale, not bytes, and not screen columns either, so be cautious when counting characters outside the ASCII set. Some Japanese characters, for example, will expand to "1" with an en_US.UTF-8 locale, even though they're 4 bytes long, and will usually take 2 screen columns.

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.