Timmmm
Timmmm

Reputation: 96556

Portable way to check if an environment variable is set

In Bash you can check if an environment variable is set with test -v FOO. It doesn't work in Dash on Debian 11 though because its test doesn't support -v:

# test -v FOO
dash: 2: test: -v: unexpected operator

Is there a portable way that works in Bash and Dash (and ideally more shells, but those are the main ones I am concerned with)?

Upvotes: 1

Views: 583

Answers (1)

Toby Speight
Toby Speight

Reputation: 30781

You can use + in the expansion of the variable, and test it:

test "${FOO+x}"

The expansion results in an empty string if FOO is unset, or x otherwise.

Upvotes: 2

Related Questions