brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: ${#var} gives the length of a bash string or array

Bash
~/tips/tip-bash-string-length-hash

key='abc123xyz'

Count characters or array items without wc or a loop.

Piping a variable into wc -c to get its length gives you one too many, because of the newline echo adds. Bash knows the length already.

Put # in front of the name inside the braces:

key='abc123xyz'
echo "${#key}"          # 9

files=(a.txt b.txt c.txt)
echo "${#files[@]}"     # 3

On a plain variable you get the number of characters. With [@] on an array, the number of elements.

I’d use it for small sanity checks, like refusing an API key that is clearly too short:

if (( ${#API_KEY} < 32 )); then
  echo "API_KEY looks wrong" >&2
  exit 1
fi

Watch the array case. Without [@], ${#files} is the length of the first element, here 5, which looks like a believable count and is easy to miss. And in a UTF-8 locale bash counts characters, not bytes, so a string with an accented letter can be one shorter than the byte count some protocols care about. Run it with LC_ALL=C if bytes are what you need.

Further reading: Bash manual: Shell Parameter Expansion

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link