Shell Scripting - Test Constructs
Last Updated :
05 Feb, 2023
Since 0 by UNIX tradition denotes "success," an if/then construct checks to see if the exit status of a list of commands is 0 and, if it is, runs one or more instructions. There is an exclusive command called [ (left bracket special character). It is a built-in synonym for test and is used for efficiency. This command uses the arguments as file tests or comparison expressions, and it returns an exit status that corresponds to the comparison's outcome (0 for true, 1 for false).
The [[...]] extended test command was added to Bash in version 2.02 and performs comparisons in a more recognizable way to programmers of other languages. Please take note that [[is a keyword, not a command. [[$a -lt $b]] is viewed as a single element by Bash and returns an exit status. If the outcome of arithmetic expressions that are evaluated by the ((...)) and let... constructions extend to a non-zero value, they return an exit status. For carrying out arithmetic comparisons, one can employ these arithmetic-expansion constructions.
Usage of Test Constructs
Example 1: Simple tests yielding true or false
Script:
#!/bin/bash
# Test that should succeed as values are equal
[1 = 1]
echo $? # Zero output implies 'true'
# Test that should fail as values are not equal
[1 = 0]
echo $? # Non-zero output implies 'false or un-true'
Output:
Note: The outcome of a single equals sign is similar to a double equals sign.
Explanation:
In the above example, it is shown that the test condition will evaluate to true only if both values are equal otherwise evaluate to false.
Example 2: Logical AND (&&)
The logical && returns true only when both conditions are true otherwise it returns false.
Syntax:
x && y or x -a y
Below is an example demonstrating the concept of logic and operator.
Script:
#!/bin/bash
echo "Enter the first number"
read x
echo "Enter the second number"
read y
if [$x == 3] && [$y == 13]
then
echo "Successful Execution"
else
echo "Not Successful Execution"
fi
Input:
3
13
Output:
Explanation:
In the above example, it is shown that the "if" test condition will evaluate to true only if both conditions are true otherwise evaluate to false. Here the standard inputs are 3 and 13 which are equal to values present in the "if" condition, therefore, resulting in successful execution.
Example 3: Logical OR (||)
The logical || returns true when either of the two conditions is true otherwise it returns false.
Syntax:
x || y or x -o y
Below is an example demonstrating the concept of logical or operator.
Script:
#!/bin/bash
echo "Enter the first number"
read x
echo "Enter the Second number"
read y
if [$x == 3] && [$y == 13]
then
echo "Successful Execution"
else
echo "Not Successful Execution"
fi
Input:
10
13
Output:
Explanation:
In the above example, it is shown that the "if" test condition will evaluate to true if any of the conditions is true otherwise it returns false. Here the standard inputs are 10 and 13 from which 13 is present in the "if" condition, therefore, the result is true.
Example 4: Logical and, or, and not
Below is an example demonstrating the concept of logical operators.
Script:
#!/bin/bash
[ 1 = 1 -a ! '0' = '0' -o '3' = '3']
echo $?
Output:
Explanation:
In the above example, logical operators are applied to the values directly and the result is evaluated as true.
- Firstly condition 1=1 is true as both values are equal, and next 0=0 is also true but because of not (!) its result becomes false.
- true -a (and operator) false becomes false
- 3=3 is true so, the previous result gets replaced with the present one i.e. false -o (or operator) true is true. Hence, the output is 0 which is true.
Example 5: Unary and Binary Operators
Below is an example demonstrating the concept of Unary and Binary Operators.
Script:
#!/bin/bash
echo $PWD
[ -z "$PWD" ] # -z is a unary operator that takes one argument
echo $? # Returns false, as PWD has content
unset DOESNOTEXIST
[-z "$DOESNOTEXIST"]
echo $?
[ -z ]$?
Output:
Explanation:
They are referred to as "unary operators" (because they take one argument). The -z command will produce a false result if your $PWD environment variable is set, which it typically is. This is due to the fact that -z only returns true if the argument is an empty string.
Script:
#!/bin/bash
[ 13 -lt 3]
echo $?
[ '13' -lt '3' ]
echo $?
[ 3 -lt 13 ]
echo $?
[ 13 -gt 3 ]
echo $?
[ 3 -eq 3 ]
echo $?
[ 13 -ne 13 ]
echo $?
Output:
Explanation:
Input and output are handled by "binary operators." In the example above, the binary operators -lt (less than), -gt (greater than), -eq (equals), and -ne were used (not equals). In single-bracket tests, they easily handle integers even when quoted.
Example 5: if Test
Syntax:
if...fi statement
if...else...fi statement
if...elif...else...fi statement
Below is an example demonstrating the concept of if condition.
Script:
#!/bin/bash
if[[ 13 -lt 3 ]]
then
echo 'FALSE'
elif [[ 13 -gt 3 ]]
then
echo 'TRUE'
else
echo 'neither greater than, or less than, so must be equal'
fi
Output:
If statements include:
- A testing condition
- then is the word
- It executes the statements after the then if the if test returns "true."
- It will if the if test returned false.
- If there is another test, move on to the subsequent elif statement.
- If there are no further tests, you can move to the else block.
- The fi string serves as the final closure for the if block.
Note: The if statement can function without the else or elif sections.
Explanation:
In the above example, it is shown that firstly 13 and 3 are compared in the "if" statement using "lt" less than the operator then in the next "if" the same values are compared using "gt" greater than the operator. In the end, if both cases are not satisfied then the last statement will be displayed. As we know, 13 is greater than 3 so, TRUE is the output.
Conclusion:
Tests are a fundamental part of bash scripting and here we have discussed test constructs in various forms. The usage of test construct in determining the true or false condition through logical operators- and, or, and not. Then unary and binary operators and simple if construct is also discussed and we found that test constructs are quite helpful in finding the exact state of the condition.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
Decorators in Python In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Linux Commands Cheat Sheet Linux, often associated with being a complex operating system primarily used by developers, may not necessarily fit that description entirely. While it can initially appear challenging for beginners, once you immerse yourself in the Linux world, you may find it difficult to return to your previous W
13 min read