test Command in Linux
Overview
In Linux, the test command is a built-in function of the bash shell. It enables us to check file types and compare values. Commonly used in scripting languages, the test command in Linux also facilitates decision making in shell scripts by evaluating conditional expressions.
Syntax of test Command in Linux
The basic syntax of the test command in Linux is as follows:
Where:
- test: This is the command itself.
- EXPRESSION: This is the condition that you want to test.
Options in test Command in Linux
-
-s FILE: This option checks if FILE exists and has a size greater than zero.
For example -
Output:
This command checks if the file 'myfile.txt' exists and is not empty.
-
-f FILE: This option checks if FILE exists and is a regular file.
For example -
Output:
This command checks if 'myfile.txt' exists and is a regular file.
-
-eq: This option checks if two numbers are equal.
For example -
Output:
This command checks if 5 equals 5.
Example Usages
-
To test if a file exists and is not empty:
Output:
Explanation: The command checks if 'myfile.txt' exists and is not empty.
-
To check if two numbers are equal:
Output:
Explanation: The command checks if 5 equals 5.
Tips
-
test command returns a status of 0 (true) and 1 (false) to enable further script control.
-
test command is often used in combination with if-else statements in bash scripts.
Advanced Use Cases of test Command in Linux
-
Combining multiple conditions:
Output:
Explanation: The command checks if 'myfile.txt' exists, is not empty, and is a regular file.
-
Using 'test' command within an if-else construct:
Output:
Explanation: The command checks if 'myfile.txt' exists and is a regular file, and prints a corresponding message.
-
Checking for inequality using 'test' command:
Output:
Explanation: The command checks if 5 is not equal to 10.
Conclusion
-
The test command in Linux is a versatile tool for evaluating expressions, commonly used within scripts.
-
It returns a status of 0 for true and 1 for false, useful for script control flow.
-
The test command can check for file properties and compare numerical or string values.
-
It can be used in complex expressions by combining multiple conditions.