1

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)
mjarosie
  • 113

1 Answers1

2

Explicitly choose an interpreter by specifying a shebang. There is no shebang in your current script. When called from zsh such script runs with sh. Apparently whatever provides sh in your system does not support [ -v …. Zsh supports this, Bash supports this, other shells may not.

It seems you want to use Zsh, so the shebang should be #!/bin/zsh or similar. It must be the very first line of the script.