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
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
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:
One [[
test:
if [[ $first_arg == major || $first_arg == minor ]]; then
exit 1;
fi
Two [[
tests:
if [[ $first_arg == major ]] || [[ $first_arg == minor ]]; then
exit 1;
fi
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.
==
and =
equivalent for string comparison. Though it states that = should be used with the test command for POSIX conformance.
–
Jun 17 '18 at 11:52
[
command from GNU coreutils. Dash doesn't like ==
, though, and there's no advantage to using it.
– ilkkachu
Jun 17 '18 at 12:09
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.
-a
/-o
in [
/test
, but I do wonder what you refer to with macro expansion?
– ilkkachu
Jun 17 '18 at 12:10
[[ ... ]]
. – choroba Jun 16 '18 at 23:26[[...]]
will quote everything for me? – Alexander Mills Jun 16 '18 at 23:50[[ ... ]]
. See the end of my updated answer. – Jun 17 '18 at 00:08