In Bash, the test
command is used for evaluating conditions and performing various tests. It allows you to check the status of files, compare values, and perform string comparisons. The test
command can be used directly in conditional statements or with the square brackets [ ]
for improved readability. Here’s an overview of the test
command and its usage:
Basic Syntax of test
command:
test condition
Alternatively, you can use square brackets for readability:
[ condition ]
Here are some common tests that can be performed using the test
command:
- File Tests:
-e file
: True if the file exists.-f file
: True if the file exists and is a regular file.-d directory
: True if the directory exists.-r file
: True if the file is readable.-w file
: True if the file is writable.-x file
: True if the file is executable.
- String Tests:
-z string
: True if the string is empty.-n string
: True if the string is not empty.string1 = string2
: True if string1 is equal to string2.string1 != string2
: True if string1 is not equal to string2.
- Numeric Comparisons:
n1 -eq n2
: True if n1 is equal to n2.n1 -ne n2
: True if n1 is not equal to n2.n1 -lt n2
: True if n1 is less than n2.n1 -le n2
: True if n1 is less than or equal to n2.n1 -gt n2
: True if n1 is greater than n2.n1 -ge n2
: True if n1 is greater than or equal to n2.
Here’s an example that demonstrates the usage of the test
command in Bash:
#!/bin/bash
file="example.txt"
if [ -e "$file" ]; then
echo "The file exists."
else
echo "The file does not exist."
fi
In this example, the test
command with the -e
option is used to check if the file "example.txt"
exists. If the condition is true, it executes the code block following the then
keyword, which outputs “The file exists.” If the condition is false, it executes the code block following the else
keyword, which outputs “The file does not exist.”
When you run this script, it will output either “The file exists.” or “The file does not exist.” based on the existence of the specified file.
The test
command is a powerful tool in Bash for performing tests and evaluating conditions. It allows you to make decisions and control the flow of your script based on various conditions and comparisons.