[SOLVED] How to check existence of environment variable in BASH without passing it value to cmd?

Issue

Basically, I have this if statement that doing all required stuff

if [ -z "${x}" ]; then
echo "You must set x variable, please see readme.md on how to get & set this variable."
exit 1
fi

But I found a more cool solution:

echo "${x:?You must set x variable, please see readme.md on how to get & set this variable.}

It also works, but it has one major problem, if variable exist it print it to the cmd, is it possible to somehow show only error and if variable exist not to show it content?

Is it possible to pass 2 variables in that 1 function?
Something like that:

echo "${x,y:?You must set x,y variable, please see readme.md on how to get & set this variable.}

Solution

You can use a no-op (:):

: ${x:?x is empty or not set} ${y:?y is empty or not set}

Or

: ${x?x is not set} ${y?y is not set}

Be aware of the difference between empty and not set.

You can also test if a variable is set or not:

[[ -v x ]] || { echo x is not set >&2; exit 1; }

I do use the no-op thing sometimes, but usually I make a die function for errors:

die()
{
    echo "[email protected]" >&2
    exit 1
}

[[ -v x ]] || die x is not set

edit: I was wrong to say you need a test to check if a variable is set or not. I couldn’t remember the syntax and missed it in the documentation.

Like other expansion logic, you can omit the colon (:) to change the check from if empty to if not set. So ${x?} causes an error if x is not set (and no error if set and empty), ${x:?} causes an error if x is not set, or set but empty.

I modified the answer accordingly.

Answered By – dan

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.