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: [[ ]] in bash does not split variables, where [ ] does

Bash
~/tips/tip-bash-double-brackets-test

v="a b"

Know why [[ ]] is safer in bash scripts and when you still need [ ].

Both [ ] and [[ ]] test things, and in bash scripts the double form avoids a whole class of quoting bugs. The difference shows up as soon as a variable contains a space or is empty.

[ is a command, so its arguments go through word splitting and globbing first. [[ is part of the bash syntax and does not split:

v="a b"
[ $v == "a b" ]     # error: too many arguments
[[ $v == "a b" ]]   # true

An empty, unquoted variable is also fine inside [[ ]], where [ ] would see a missing argument. You can also use &&, || and < directly, without escaping them.

There are differences to know. == on the right side of [[ ]] is a pattern match, so [[ $f == *.log ]] works, and you quote the right side if you want a literal comparison. < compares as strings, so [[ 2 < 10 ]] is false; for numbers use -lt or (( )). And =~ gives you regular expressions.

I’d still quote variables inside [[ ]], it does no harm. The one place where [ ] remains the right choice is a script for /bin/sh, such as on Alpine or in a Debian maintainer script, because [[ is not POSIX.

Further reading: Bash manual: Conditional Constructs ([[ ]])

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