The “test” Command in Linux [With 5 Practical Examples]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

The “test” command is available in most Linux shells, either as a built-in function or a standalone executable file located in /usr/bin that evaluates conditional expressions. The command checks file types, compares values, and performs various logical operations, making it versatile for scripting. It is useful in complex expressions by combining multiple conditions.

In this tutorial, you will learn about the “test” command in Linux with detailed explanations, basic-to-advanced usage, and helpful tips.

Syntax of “test” command in Linux

The basic syntax of the “test” command is:

test EXPRESSION

or

[ EXPRESSION ]
EXPLANATION
  • test: The command itself.
  • EXPRESSION: The condition that you want to test. It can be a comparison between two numbers, a check on a file, or a logical operation.

Note: [ EXPRESSION ] or simply [] is a short form of the “test” command syntax.

Options of “test” command in Linux

Some common options of the “test” command are:

Option Function
-s FILE Checks if FILE exists and has a size greater than zero.
-f FILE Tests if FILE exists and is a regular file.
-eq Checks if two numbers are equal.

How to Install “test” Command in Linux?

The test command is typically part of the coreutils package, which is pre-installed in most Linux distributions. Anyway, if it’s not installed on your system, you can install it by using the following commands:

➊ To install the “test” command in Debian-based Linux distributions like Ubuntu, use the APT package manager. Here is the command:

sudo apt-get install coreutils

➋ To install the “test” command in RPM-based Linux distributions like CentOS, use the YUM package manager. Run the below command:

sudo yum install coreutils

➌ To install the ‘test’ command from its source code, you can clone the “coreutils” repository that includes the “test” command. This is particularly useful if you want to use a specific command version. Use the below website link:

git clone git://git.sv.gnu.org/coreutils

After cloning, you can now compile and install “test” from the source code.

How to Use “test” Command in Linux?

To use the “test” command for evaluating a condition, for example, checking if a directory exists or not, run the following command on the terminal:

test -d /usr/local/bin

Note: You can also use square brackets [] instead of “test” for the same result, for example: [ -d /usr/local/bin ]

The successful execution of the test command displays no output on the terminal. To find the exit status of the command (to check whether the command ran successfully), use the variable $? with the echo command after execution. The full syntax is:

echo $?

Checking directory using test command and variable $?

The command checks if the directory exists and then it returns 0 as exit status if the condition is True. It returns a non-zero value if the condition is False. Which you can see from the return value of the echo $? variable.

Now, another approach to getting the display result of the test command is by using the logical operators to combine test with another command that prints the output status.

To get a confirmation message after running the “test” command, simply use && (AND) or || (OR) logical operators with the “echo” command. Where, the AND (&&) operator produces a true outcome when every condition is true. On the other hand, the OR (||) operator evaluates to true if at least one of the conditions it connects is true. For example:

test -d /usr/local/bin && echo “Directory exists.”

Showing confirmation message using test command with logical operators &&

Running the command prints a confirmation message in this case “Directory exists” as the condition is True.

5 Practical Examples of Using “test” Command in Linux

Here are a few examples of using the “test” command in Linux:

1. Testing for a File

To test for a file’s existence, you can use the test command with -e option. Testing a file is crucial to avoid clobbering i.e. creating multiple files under the same names. Here is a command to test for a file with a confirmation message:

test -e states.txt && echo "File exists"

Testing the existence of a file using test command with -e option

As you can see, the command prints a confirmation message because the file actually exists.

2. Testing File Types

To test a variety of different file types, you can use the test command with various options. Here are some command file types:

  1. To test for a regular file, use test with the -f option. Here is the command:
    test -f states.txt && echo “Regular file”

    Checking for a regular file using test with -f option

    Upon running, the command returns true because it is a regular file and “echo” displays that message.

  2. To test for a directory, use test with -d. Run the command below:
    test -d /usr/local/bin && echo “Directory”

    Checking directory using test command with -d option

    Hence, the command returns true for the given file as a directory.

  3. To check if a file is a block special file, use test followed by the -b option. A block special file is a device file that provides buffered input/output operations. These files are used to interact with block devices such as hard drives and SSDs. For example:

    test -b /dev/sda && echo “Block file”

    Checking for a block special file using test command with -b option

    After execution, the command returns true since the specified file is a block file.

  4. To test files with symlinks, use test along with -L or -h. A symlink is a special type of file that acts as a pointer or shortcut to another file or directory. Use the following command to do so:

    test -L symlink.txt && echo “Symbolic link”

    Testing files for symlinks using test with -L option

    Thus, the command returns true as the given symlink.txt is a symbolic link file.

  5. To check if a file is a socket, apply test with -S. A socket is a special file used for inter-process communication between processes on the same or different computers. See the below command:

    test -S /tmp/socket/my_socket && echo “Socket file”

    Checking for a socket file using test command with -S option

    Upon execution, the command returns true as the specified file is a socket file.

3. Testing for File Attributes

To test for file attributes for a given file, you can use the test command in Linux. Here are a few cases you can use the command for file attributes:

3.1 Searching Metadata of a File

To search metadata of a file, you can use the test command with -s and -N options. Here are the commands:

  1. To check if the size of a file is greater than zero, use -s option. The command:
    test -s states.txt && echo “Size greater than zero”

    Comparing file sizes using test command with -s option

    The command returns true because the size of states.txt is actually greater than zero.

  2. To check if a file has been modified since the last read, use -N option. Run:
    test -N states.txt && echo “Modified since last read”

    Checking if the file has been modified since last read using test command with -N option

    As a result, it returns true because the specified file has been modified since it was last read.

3.2 Testing by Ownership

To test a file by ownership, you can use the test command in Linux. Here are the cases:

  1. To test a file owned by the current primary user, use test command with -O option. Run the command below:

    test -O states.txt & echo “Owned by current user”

    Testing a file owned by the current primary user using test -O

    Since the states.txt file is owned by the current primary user, the command returns true.

  2. To test a file owned by the current primary group, use the test command followed by the -G option. The command:

    test -G states.txt && echo “Owned by current group”

    Testing for group owned using the test command with -G option

    The command returns true because the current group owns the specified file.

3.3 Testing by Permissions

To test files by current permissions, use the test command. Follow the few cases of different permissions:

  1. To test a file with read permission granted, use test command with -r option. Run the command below:
    test -r log.txt && echo “Read permission granted”

    Testing for read permission using test command with -r option

    This command checks if the file log.txt has read permission granted.

  2. To test a file with write permission granted, use the test command with the -w option. Here is the command:

    test -w log.txt && echo “Write permission granted”

    Checking for write permission using test with -w option

    Running the command checks if the current user has write permission for the file named log.txt and shows output if true.

  3. To test files with execute permission granted, use the test command with the -x option. For example, use the command below:

    test -x log.txt && echo “Execute permission granted”

    Testing for execute permission using -x command

    Hence, this code checks if log.txt has the execute permission set and, if so, prints a message.

  4. To check a file with the sticky bit set, use the test command with the -k option. The sticky bit is a special permission that controls how to delete or modify files within the directory or system. Here is the command to do so:

    test -k log.txt && echo “File has sticky bit set”

    Checking for sticky bit set for files using test command with -k option

    Upon running, the command returns true as the specified file has a sticky bit set.

4. Combining Tests

You can combine multiple conditions and perform AND or OR operations, using the test command with -a or -o options. The -a option (AND) lets you combine multiple tests, checking all tests to be true for the entire condition to be true. The -o option (OR) requires that at least one expression is true for the entire condition to be true.

Suppose, you have two files named colors.txt and puppy.png. Let’s create combining tests with them:

  1. To combine multiple tests with AND operations, use test command with -a option. For example:
    test -e colors.txt -a -e puppy.png && echo “Correct”

    Combining multiple tests with test and AND operators

    The command returns true since you have both files.

  2. Now, try to use the command to search for one of the files, that does not exist:
    test -e colors.txt -a -e kitty.png && echo "Correct"

    Using a non-existential file in AND operator

    See from the image that the command returns no output because one of the conditions is false.

  3. To combine multiple tests with OR operations, use the test command with the -o option. Use the below command:

    test -e colors.txt -o -e kitty.png && echo "Correct"

    Performing OR operation using test -e option

    As you can see, the -e option returns true for at least one true expression even though the kitty.png file does not exist in my system.

5. Testing Integers

To test integers, you can also use the test command in Linux. This is particularly useful when you’re using variables with assigned integers in a script. Run the below commands to test if  two variables are equal or not using the -eq option:

apple=33
banana=32
test $apple -eq $banana || echo “Not equal”

Comparing two integer variables using test with -eq option

The command returns false as the -eq expression is false.

Here are some other options to compare integers while using the “test” command:

Options Function
-ne Not equal
-ge Greater than or equal to
-gt Greater than
-le Less than or equal to
-lt Less than

Advanced Use Cases of “test” Command in Linux

Here are a few advanced use cases to dive deeper into the usage of the “test” command in Linux:

1. Using “test” Command in Scripts

The ‘test’ command is incredibly useful in shell scripting. It allows you to dictate script behavior based on specified conditions.

Here’s a simple example of using “test” command within a shell script:

  1. Run the following command to open the nano text editor:
    nano test.sh
  2. Paste the following “test” command in the Nano editor:
    #!/bin/bash
    
    if test -d /usr/local/bin; then
     echo “ Directory exists.”
    else
     echo “Directory does not exist.”
    fi
    EXPLANATION

    The script checks if the directory specified exists and prints a corresponding message depending on the result of the check.

  3. Give execution permission to the user using the below command:
    chmod u+x test.sh
  4. Lastly, run the below command:
    ./test.sh

    Using test command in scripts

    This way you can perform more advanced “test” operations in Scripts.

2. Altering “test” Command Behavior Using Negation Operator

You can alter or reverse the behavior of the “test” command using a negation operator !. The ‘!’ operator in the test command negates the result of the condition that follows it. If the condition is true, the ‘!’ operator makes it false, and vice versa.

Here is an example of using the “test” command with “!” operator:

test ! -d /usr/local/bin && echo “Directory exists.”

The command with && operators returns no output since the “!” option reverses the expression.

test ! -d /usr/local/bin || echo “Directory exists.”

In this case, the command with || operators returns an output because of the “!” option reversing the expression.Altering test command’s behavior using “!” operator

Conclusion

In summary, the “test” command in Linux is a versatile tool for evaluating expressions, commonly used within scripts. Hopefully, you can now check for your file properties and compare numerical or string values. If you have any further questions, please write them in the comment box below.

People Also Ask

Why do we use “test” command in Linux?

We use the “test” command to check the type of file and the permissions related to a file. Test command returns 0 as a successful exit status if the command/expression is true, and returns 1 if the command/expression is false.

What is the difference between “[” and “test” commands in Linux?

The main difference between “[” and “test” commands is in their origin. The “[” is a shell built-in equivalent to the test command that doesn’t require a separate program execution. The “test” command is a separate executable file located in /usr/bin.

Why is the output value different for -z and -n with “test” command in Linux?

The “test” command evaluates the condition and indicates the result of the evaluation by its exit status. An exit status of zero indicates that the condition is evaluated as true and an exit status of 1 indicates that the condition evaluates as false. The “-n” string is True if the length of the string is non-zero. The “-z” string is True if the length of the string is zero.

Can I use the “test” command within an if-else construct in Linux?

Yes, you can use the “test” command within an if-else construct in Linux. If-else statements rely on the exit status of commands (0 for success, non-zero for failure). The “test” command follows this convention, making it perfect for use within if-else constructs.

Rate this post
Avatar photo

Yousuf Shovon is a Linux Content Developer Executive (LCDE) at SOFTEKO. Previously, he worked for ExcelDemy, writing over 60+ articles on Excel. His goal is to write quality content for users to read and learn. In the future, he also wants to build various projects with LinuxSimply. He completed his graduation and post-graduation in Information Technology from Jahangirnagar University. Yousuf finds joy in solving diverse Linux-related problems to gain an all-around experience in Linux. Read Full Bio

Leave a Comment