WIP Alert This is a work in progress. Current information is correct but more content will probably be added in the future.
Bash in an extension over the POSIX shell, so everything that works in the POSIX shell can also be used in bash.
Tests and if-then-else constructs
test command is present in most shells and it tests whether a boolean expression is true or false. You use it via
Bash and POSIX-compliant shells have also
if constructs, and these are usually used together with
The two following snippets for testing whether two variables are the same are therefore equivalent:
# using test on its own [ "$a" -eq "$b" ] && echo 'a and b are equal' # equivalent: using if construct if [ "$a" -eq "$b" ]; then echo 'a and b are equal' fi
You need to place a variable within double quotes whenever there's the risk that it might contain special characters such as
\ and so on.
Test If Two values are Equal / Different
to compare strings use
foo='foo' if [ "$foo" = 'foo' ];then echo 'equal' elif [ "$foo" = 'bar' ];then echo 'something else' else echo 'not equal' fi
for booleans, use
b1=true b2=false # -a means AND and -o means OR if [ $b1 = true -a $b2 = true ];then echo 'they are not both true' elif [ $b1 = false -a $b2 = true ];then echo 'they are not both false' elif [ $b1 = true -o $b2 = false ];then echo 'at least one of them is true' else echo 'something else' fi
to compare numbers use
# was last command a success? if [ "$?" -eq 0 ]; then echo 'great success!' else echo 'failure' fi