Linux shell if test

Using test Command in Bash Scripts

Learn to use the test command in bash for testing conditions and making comparisons.

The bash test command is used to check the validity of an expression. It checks whether a command or an expression is true or false. Also, it can be used to check the type and permissions of a file.

If the command or expression is valid, the test command returns a 0 else it returns 1 .

Using the test command

The test command has a basic syntax like this:

When using variables in the test command, use double quotes with the variable’s name.

Let’s use the test command to check whether 10 equals 20 and 10 equals 10:

$ test 10 -eq 20 && echo "true" || echo "false"
  • test — test command
  • 10 — the first variable
  • -eq — operator for comparison
  • 20 — second variable

If the given expression is valid, the first command is executed, or else the second command is executed.

💡Instead of using the test command keyword, you can also use the brackets [] . But remember, there is space between the [ mark and the variables to compare:

[ 10 -eq 20 ] && echo "true" || echo "false"

test command examples

Not only integers; you can also compare strings in bash with the test command. Let me share some examples.

String comparison with test Command

Here are some string comparison examples using the test command.

Check if the string is not empty

The -n flag checks if the string length is non-zero. It returns true if the string is non-empty, else it returns false if the string is empty:

$ [ -n "sam" ] && echo "True" || echo "False"

Check that string is not empty in bash

Check if the string is empty

The -z flag checks whether the string length is zero. If the string length is zero, it returns true, else it returns false:

$ [ -z "sam" ] && echo "True" || echo "False"

Check if strings are equals

The ‘=’ operator checks if string1 equals string2. If the two strings are equal, then it returns 0; if the two strings are not equal, then it returns 1:

In this case, the expression is slightly different, instead of typing true or false, the stdout variable is printed using $? .

Check if strings are not equals

The != operator checks if String1 is not equal to String2. If the two strings are not equal, then it returns 0. If two strings are equal, then it returns 1:

Читайте также:  Как работает traceroute linux

Integer comparison with test command

Let’s make some number comparisons with bash test.

Check if numbers are equal

The -eq operator checks if Integer1 equals Integer2. If integer1 equals integer2, then it returns 0, else it returns 1:

Check if the numbers are not equal

Case 2. The -ne operator checks if integer1 is not equal to integer2. If Integer1 is not equal to integer2, then it returns 0, else it returns 1:

Check if a number is equal or greater than the other

The -ge operator checks that integer1 is greater than or equal to integer2. If integer 1 is greater than or equal to integer 2 it returns 0; if not, then it returns 1.

The -gt operator checks if integer1 is greater than integer2. If yes, then it returns 0. Otherwise, it returns 1:

Check if a number is equal or less than the other

The -le operator checks if the integer1 is less than or equal to integer2. If true it returns 0, else it returns 1:

The -lt operator checks if integer1 is less than integer2. If integer 1 is less than integer2, then it returns 0, else it returns 1:

Integer comaprison in bash using the test command

File and directory Operations with test

The test command can be used with files and directories.

This checks whether a file is executable (by the current user) or not. If a file is executable, then it returns 0, else it returns 1:

[ test -x filename ] && echo executable || echo non-executable

You can use other file permissions like r and w in the same fashion. Other common parameters you can use are:

| Command | Description | |---------|--------------------------| | -e | File/directory exists | | -f | is a file | | -d | is a directory | | -s | File size greater than 0 | | -L | is a link | | -S | is a socket |

Using test command in bash scripts

You have seen the one-liners of the test command so far. You can also use the test condition with the if-else condition in the bash scripts.

Let me share a simple example of comparing two numbers passed as arguments to the shell script:

#!/bin/bash ## Check if the numbers are equal or not read -p "Enter the first number: " num1 read -p "Enter the second number: " num2 if test "$num1" -eq "$num2" then echo "$num1 is equal to $num2" else echo "$num1 is not equal to $num2" fi

You can run the bash script with various numbers:

Using test in bash scripts

I hope this tutorial helps you to understand the basics of the test command in the bash.

Источник

Bash if –e and –s and other File Test Operators

In Linux files, test operators are used for checking the attributes associated with a file like: the author of the file, administrative rights, and ownership of the file, and to check whether they are symlink or not. When we are dealing with files, it becomes necessary to check their existence and whether they contain any content or not for this purpose; or if a statement is used along with the test operators.

File test operators in bash are also used to test the files as the name explains. With the help of these operators, we can test different aspects of a file like if that file is writable or readable only. There are many file test operators and each one has a different role and use. File test operators help us to prevent errors while scripting in Bash. To perform that task, we use an if-else statement. The if-else statement acts as a very useful tool for error handling in Bash scripting.

Читайте также:  Связка ключей linux браузер

The purpose of the “-e” operator is to tell us whether a file exists in the specified directory or not. The “-s” operator tells us that the file is not a zero size which means that this operator tells us whether the file in the specified directory contains any data or not. Other operators are used to dealing with files but the “-e” and “-s” are the most important ones and are frequently used.

How to Use Test Operators:

In this illustration, we will try to use all of the test operators to perform various tasks on the files.

Example no. 1: Using the if –e Text Operator

In this example, we will try to use the if –e test operator which is mainly used to verify whether the file exists in a directory or not. Now, we will first create a new file.

When we run the command above, it will open the empty file now we will write the code in which we will create a condition that the file “employee.txt” exist it will display the echo command which contains the message “File exists”. Else, it will execute the message “File does not exist”. The file testoperator will contain the content mentioned below.

#!/bin/sh
file = «employee.txt»
if [ -e $file ]
then
echo «File exists»
else
echo «The file does not exist»
fi

After saving the file using the bash command, we will run the below-mentioned command which will execute the testoperator.sh file.

When we run the above command, it will read the code of the testoperator file which executes and check for the file in the home directory. In this case, we do not have any file in the directory, so it executed the output below.

Now, we will first create a new file named “employee.txt”. Then, again run the command to check whether it will detect the file or not. As shown below, this time the file exists in the home directory.

Now, let us run the above command again. This time, it displays the output that is shown below in which the message “File exists”.

Example no. 2: Using the if –d Text Operator

In this example, we will try another test operator that is the “-d” operator which is used to verify whether the file we are checking is a directory or not. This time, we will create a new directory which we named “employee”, as can be seen in the snippet below.

Now, we will modify the “testoperator.sh” file in which we will change the file name “employee.txt” to just “employee”. Then, passing the “-d” operator in the if statement along with the “$file” which will be fetched out. And changing the message, that will be displayed as output, we will save the file. Now, the “testoperator.sh” file contains the following content.

Читайте также:  Installing netcat on linux

#!/bin/sh
file = «employee”
if [ -d $file ]
then
echo » The employee is a directory »
else
echo » The employee is not a directory »
fi

After modifying the “testoperator.sh”, we will run the bash command along with the file name :

When the command above executes, it will display the output shown below in which it prints the message that is:

Example no. 3: Using the if –s Text Operator

In this example, we will try to use the “-s” operator which is used to check whether the file contains any content or not. For that, we will be using the already created file that we used in example 1 named “employee.txt”. Let us first modify the file testoperator.sh in which we will pass the “-s” option along with the file name to our if statement and assign the file “employee.txt”. Also, it will change the message that will be displayed as an output.

#!/bin/sh
file = «employee.txt”
if [ -d $file ]
then
echo » employee.txt is empty »
else
echo » employee.txt is not empty »
fi

Now, we will save and close the file “testoperator.sh” and run the command mentioned below in the terminal.

When the command above runs, it will execute the else statement because the employee.txt contains the content. So, it ignores the then statement echo command.

Now, we will remove the content from the “employee.txt” and then run the command again. When the command above is executed once again, it displays the then statements message because it does not contain any content in it. The example below is the output of the command that we executed after deleting the content of the file.

Example no. 4: Using the if –r Text Operator

In this example, we will implement another test operator that is “-r”. This operator is used to check whether the file is readable to the user or not. For this, we will modify the testoperator.txt file by replacing the “-d” operator with “-r”. It will also change the output message which is if the file is readable. It will display the message “employee.txt is readable and if the file is not readable it will display the else statement. Now, the “testoperator.txt” contains the following content:

#!/bin/sh
file =”employee.txt”
if [ -r $file ]
then
echo “employee.txt is readable”
else
echo “ employee.txt is readable “
fi

Now, we will run the command below to execute the code written inside it.

After running the above command, the displayed output below will be printed on the terminal.

Conclusion

We have discussed the most important part of the filing system, the test operators. While working with files, the test operators are the most essential utility provided by Linux packages. After introducing the purpose of the test operators, we explained them by implementing these operators in various examples.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.

Источник

Оцените статью
Adblock
detector