Skip to content
shellhacks.dev
Bash

Test if a variable is set without expanding it

Test whether a variable is set, even to an empty string, with [[ -v name ]] in Bash 4.2 or later. It tells unset apart from empty without expanding.

1 min read
Summarize in AI

A variable can be empty or it can be unset, and [[ -z $x ]] cannot tell the two apart. The -v test can.

Shell
a=""
unset b
[[ -v a ]] && echo "a is set"
[[ -v b ]] || echo "b is unset"
[[ -n $a ]] || echo "yet [[ -n \$a ]] is false for a"
set -u
[[ -v b ]] || echo "no error under set -u"
Text
a is set
b is unset
yet [[ -n $a ]] is false for a
no error under set -u

[[ -v name ]] is true when the variable has been assigned a value, including the empty string, and it takes the name rather than the expansion, so set -u does not abort the script on an unset variable. The test is listed under Bash conditional expressions.

It needs Bash 4.2 or later, and it is not in POSIX sh. In a portable script use ${name+x}, which expands to x only when the variable is set. On an array element, [[ -v arr[2] ]] works from Bash 4.3.

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.