Tests
Explore how to implement conditional expressions in Bash scripts by mastering tests with single and double brackets, logical operators, and if statements. Understand unary and binary operators, how Bash handles variables and types, and the differences between [ and [[ to write effective conditional code.
We'll cover the following...
How Important is this Lesson?
Tests are a fundamental part of bash scripting, whether it’s on the command line in one-liners, or in much larger scripts or chains of commands.
What Are Bash Tests?
A test in bash is not a test that your program works. It’s a way of writing an expression that can be true or false.
Tests in bash are constructs that allow you to implement conditional expressions. They use square brackets (ie [ and ]) to enclose what is being tested.
For example, the simplest tests might be:
Note: The
echo $?command above is a little mystifying at this stage if you’ve not seen it before. We will cover it in more depth in a lesson later in this ‘Scripting Bash’ section of the course. For now, all you need to understand is this: the$?variable is a special variable that gives you a number telling you the result of the last-executed command. If it returned true, the number will (usually) be `0’. If it didn’t, the number will (usually) not be ‘0’.
Things get more interesting if you try and compare values in your tests. Think about what this will output before typing it in:
A single equals sign works just the same as a double equals sign. Generally I prefer the double one so it does not get confused with variable assignment.
What is ‘[’, Really?
It is worth noting that [ is in fact a builtin, as well as (very often) a
program.
and that [ and test are synonymous:
Note:
whichis a program (not a builtin!) that tells you where a program can be found on the system.
This is why a space is required after the [. The [ is a separate command and spacing is how bash determines where one command ends and another begins.