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^^} and ${var,,} change the case of a bash variable

Bash
~/tips/tip-bash-case-modification-upper-lower

name=jellyfin

Turns a bash variable into upper or lower case without tr or awk.

Every time I see tr '[:lower:]' '[:upper:]' in a script just to compare an answer, I want to point at this. Bash has had case conversion built in since version 4.0.

Two carets make the whole value uppercase, two commas make it lowercase. A single caret or comma only touches the first character:

name=jellyfin
echo "${name^^}"   # JELLYFIN
echo "${name^}"    # Jellyfin

answer=YES
echo "${answer,,}" # yes

Where I’d reach for it is input you don’t control. Someone types Y, y or Yes, and you want one check that handles all of them:

read -rp "Restart the container? " reply
if [[ ${reply,,} == y* ]]; then
  docker restart jellyfin
fi

It works on arrays too. "${apps[@]^}" capitalises the first letter of every element, which is handy for a quick menu or a log line. You can also give it a pattern, like ${name^^[aeiou]}, and then only the matching characters change case. The manual says that pattern should only match one character at a time.

Two things to keep in mind. The value itself doesn’t change; you get a converted copy, so assign it back (name=${name^^}) if you want to keep it. And it needs bash 4.0 or newer, so a script that has to run under a very old /bin/bash or under plain sh will stop with an error. Check with bash --version when in doubt.

Further reading: bash(1) manual page

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