I want to check if the given variable is set with the -v check. I'm struggling to understand where the error is coming from. Having the following script in a file var-test.sh:
MY_VAR="test"
if [ -v MY_VAR ]; then
echo "MY_VAR set to $MY_VAR"
else
echo "MY_VAR not set"
fi
when I run it: ./var-test.sh I get the following output:
./var-test.sh: line 3: [: -v: unary operator expected
MY_VAR not set
But when I invoke the following command in the shell prompt:
MY_VAR="test"; if [ -v MY_VAR ]; then echo "MY_VAR set to $MY_VAR"; else; echo "MY_VAR not set"; fi
the shell doesn't complain about the -v operator and outputs "MY_VAR set to test" as expected. What gives? Am I missing something obvious?
I thought it's because of using single brackets. When I switch to using double brackets:
MY_VAR="test"
if [[ -v MY_VAR ]]; then
echo "MY_VAR set to $MY_VAR"
else
echo "MY_VAR not set"
fi
I get the following error:
./var-test.sh: line 3: conditional binary operator expected
./var-test.sh: line 3: syntax error near `MY_VAR'
./var-test.sh: line 3: `if [[ -v MY_VAR ]]; then'
The output of zsh --version:
zsh 5.7.1 (x86_64-apple-darwin19.0)
man zshsay? If that manpage just slightly resembles whatman bashcontains - then you might wish to use the (less -command)/-key to enter something to search for, maybeVARIABLE EXPRESSIONfor example. – Hannu Jan 11 '21 at 17:14#!/bin/zsh) line in your script, so maybe it's not executed with zsh?! – mpy Jan 11 '21 at 17:50