Tests
In this lesson, you'll learn some of the pitfalls and rules of thumb for practical usage of tests. You'll learn about how bash tests can be written, binary, unary, and logical operators, and if statements.
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:
[ 1 = 0 ] # Test that should failecho $? # Non-zero output means 'un-true'[ 1 = 1 ] # Test that should succeedecho $? # Zero output means 'true'
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=1[ $A = 1 ]echo $?[ $A == 1 ] # Does a double equals sign make any difference?echo $?[ $A = 2 ]echo $?
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.
which [ # Tells you where the '[' program istype [ # Tells you that '[' is also a builtin
and that [
and test
are synonymous:
which testman test # Hit q to get out of the manual page.man [ # Takes you to the same page.
Note:
which
is 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. ...
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy