Reputation: 49260
I have a Bash script as the following.
#!/bin/bash
if [ "1" -eq "1"
then echo "something"
else echo "some other thing"
fi
When i execute the script, I get the following output
test.sh: line 2: [: missing `]'
some other thing
which is unclear to me, as I excepted the script to exit with an error. Can this be explained in more detail if it is an expected behavior?
However when i use the compound command [[
#!/bin/bash
if [[ "1" == "1"
then echo "something"
else echo "some other thing"
fi
i do get the error and the script stops executing further.
test.sh: line 2: syntax error in conditional expression
test.sh: line 3: syntax error near `then'
test.sh: line 3: `then echo "something"'
Upvotes: 1
Views: 69
Reputation: 295619
[
is not bash syntax, it's just a command (a command with a shell-builtin implementation available as a performance optimization, yes, but subject to the same parse-time behavior as the standard /bin/[
external implementation or any other command). Putting an invalid ping
command or an invalid grep
command in the same position doesn't make your script's syntax invalid either.
By contrast, [[
is actual syntax, which is what makes the features it has over [
(a set which includes recognizing patterns without expanding them as globs, suppressing string-splitting and glob expansion, letting &&
and ||
to be used to combine tests, etc) possible, and also makes invalid usage able to cause a parse error.
If you want to reduce confusion to readers, consider using the name test
in place of [
. While [
and test
are typically aliases to the same command (with the only difference in behavior being whether ]
is required), it's much more visually clear to readers that if test 1 -eq 1; then
is running a command named test
and not some kind of special shell syntax.
Upvotes: 3
Reputation: 4896
$ type [[ [
[[ is a shell keyword
[ is a shell builtin
[
is an ordinary built-in. [[
is a shell keyword, and it has special syntactic significance (e.g., variables do not undergo word splitting). So an invalid usage of [[
can be a parsing error, stopping the script from being parsed correctly, whereas similar usage of [
is just the built-in returning a non-zero exit code with possibly some error output. It makes no more difference to the shell than does, say, false
returning a non-zero exit code.
Upvotes: 1