user1934428 user1934428 - 1 year ago 71
Linux Question

zsh: raise error when variable not defined

One nasty aspect with zsh (or with shell scripting in general) is, that if you mistype a variable name, and the resulting name doesn't exist, it is silently treated as empty string, which makes bugs hard to find:

if somecondition
echo $MyVar # Oops

I know that this rule exists for compatibility with good old Bourne shell. I also am aware that I can explicitly catch this error when accessing a variable:

echo ${MyVar?NOT SET}

But if I do this on every variable access, it results in ugly code. Since I have the habit to explicitly initialize all my variables, I'm looking for some way that zsh automatically spills out an error message, when a shell variable or environment variable is accessed, which hasn't been set. Is there a way to do this? I already checked the
man-page, but didn't found anything suitable.

Answer Source

In not just zsh but other shells as well, set -u makes references to unset variables an error.

That said, many scripts will not work unmodified when using this option: [[ $foo ]] can no longer be used to check whether foo was provided by the outer environment, requiring [[ ${foo-} ]] instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download