Perhaps this applies to more than just bash, but I am confused about the role of brackets in if-statements. Most examples seem to have the following format
if [ expression ]; then
#do stuff
fi
But this doesn't always work for me. For example I have the following script test.sh
:
#!/bin/bash
flag=False
if ! $flag; then
echo "No brackets: Flag is $flag"
fi
if [ ! $flag ]; then
echo "With brackets: Flag is $flag"
fi
echo "The end."
Which prints
$ ./test.sh
No brackets: Flag is False
The end.
So the statement using brackets is either ignored or it evaluates to False. Why does this happen? What do the brackets do?
I've also seen double brackets. How are those used?
--
Edit: the questions claimed as duplicates (this and this) answer only a small part of this question. I'm still unclear why the syntax with brackets would fail (it seems to me that test ! false
should evaluate to true
) and why the syntax without brackets succeeds (although, as @ilkkachu mentions in the comment, it seems like it should actually fail as well?).
flag=False; if ! $flag ; then ...
should give you an error, unless you really have a command calledFalse
. (false
would be standard, however) – ilkkachu Jun 07 '17 at 22:33if [ !$flag ]; then
works (no space between!
and$flag
) – Michael D. Jun 12 '17 at 19:48False
and "True" work just fine. rolleyes) – ilkkachu Nov 15 '18 at 18:53