0

I have a shell script like this,

#! /bin/sh
if [ -z "$ENVIRON" ]; then
    echo "no env set"
elif  [ "$ENVIRON" == "test" ]; then
    echo "test mode"
else
    echo "production mode"
fi

when I run this im getting error,

[: test: unexpected operator

I also tried changing to elif [ $ENVIRON == "test" ]; then, but getting the same error. When I run this on my mac I get the expected result:

tw tmp $ cat script.sh 
#! /bin/sh
if [ -z "$ENVIRON" ]; then
    echo "no env set"
elif  [ "$ENVIRON" == "test" ]; then
    echo "test mode"
else
    echo "production mode"
fi
tw tmp $ ENVIRON=test sh script.sh 
test mode

But getting error while running the exact same script in ubuntu

What am I doing wrong and how to fix this?

Kamrul Khan
  • 3,260
  • 4
  • 32
  • 59
  • `==` is not valid in `[`; see the specification describing its behavior in https://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html – Charles Duffy Aug 23 '22 at 20:00
  • @CharlesDuffy: it's valid in some shells such as Bash – Arkadiusz Drabczyk Aug 23 '22 at 20:00
  • @ArkadiuszDrabczyk, as a nonportable extension yes, but `sh` is not guaranteed to offer any such extensions. And if someone wants extended test syntax, they should be using `[[` instead to be explicit about that. – Charles Duffy Aug 23 '22 at 20:01

1 Answers1

1

Use single =:

elif  [ "$ENVIRON" = "test" ]; then

See https://github.com/koalaman/shellcheck/wiki/SC2039#testing-equality

Arkadiusz Drabczyk
  • 11,227
  • 2
  • 25
  • 38