1

Just wondering if this:

if [ "$first_arg" == "major" ] || [ "$first_arg" == "minor" ]; then
        exit 1;
fi

is the same as this:

if [ "$first_arg" == "major" || "$first_arg" == "minor" ]; then
      exit 1;
fi

2 Answers2

5

They're not the same. In fact [ "$first_arg" == "major" || "$first_arg" == "minor" ] is not even a valid expression.

This is because [ is a command that's equivalent to test and they can't use the || alternative, which operates on the inter-command level. What could be historically considered correct for alternative is -o, but it's now marked as obsolete by POSIX1, which advises to rewrite

test "$1" -o "$2"

into

test "$1" || test "$2"

Apart from the test and [ constructs, there's also the "modern" [[ test command, which in turn doesn't accept -o altogether, but instead accepts ||.

Thus all of these are valid and equivalent:

  1. One [[ test:

    if [[ $first_arg == major || $first_arg == minor ]]; then
        exit 1;
    fi
    
  2. Two [[ tests:

    if [[ $first_arg == major ]] || [[ $first_arg == minor ]]; then
        exit 1;
    fi
    
  3. Two [ tests (the standard equivalent):

    if [ "$first_arg" = major ] || [ "$first_arg" = minor ]; then
        exit 1;
    fi
    

Double quotes aroung $first_arg are not necessary inside [[, as there's no word splitting nor pathname expansion in there. The quotes should be used with [, however. And there's no point in quoting minor nor major either. Not just here, but with test or [ too. That's because they're simple strings.

1. See APPLICATION USAGE.

ilkkachu
  • 138,973
1

Since both of your expressions are not valid, there is a quasi equivalence ;-)

Note that == is only valid with the non-standard [[ oparator.

In general: when using the test builtin, it is recommended to use only simple expressions as larger expressions could result in unpredictable results in case that parameter expansion applies.

Since the test is built into the shell since approx. 35 years, calling more simple test commands and combine them at shell level is not a performance problem anymore.

schily
  • 19,173