Skip to content
shellhacks.dev
Bash

Get the length of a string

Get the length of a string in Bash with ${#var}. It counts characters in a UTF-8 locale and bytes in the C locale, so the same string reports two numbers.

1 min read
Summarize in AI

You need the length of a variable without calling wc or expr, and the string may hold accented letters.

Shell
LC_ALL=C.UTF-8 bash -c 's=héllo; echo "utf-8 locale: ${#s}"'
LC_ALL=C bash -c 's=héllo; echo "C locale: ${#s}"'
Text
utf-8 locale: 5
C locale: 6

${#var} is parameter expansion that returns the length of the value, and Bash measures it in characters as defined by the current locale. The letter é is one character but two bytes in UTF-8, so a shell started with LC_ALL=C counts six and one started with a UTF-8 locale counts five. No process is forked either way.

The count follows LC_ALL, LC_CTYPE and LANG, so a script run from cron or a container with no locale set may print the byte count. When you need bytes on purpose, set LC_ALL=C for that one command, and prefer wc -c for the size of a file.

Share

More snippets

Bash

Strip a file extension

Strip a file extension in Bash with ${f%.*}, which removes only the shortest suffix after the last dot and needs no basename call or subshell.

1 min read
Bash

Strip every extension from a name

Remove every extension from a name with ${f%%.*} in Bash. The doubled percent sign takes the longest match, where a single one stops at the last dot.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.