Linux test Command: Testing Conditions & Expressions in Shell Scripts
The test command is a great tool for testing conditions. Based on the return variable of the test command, programming logic can be built to execute something if a condition is met or not.
It can test conditions on files, permissions, text, numbers, and even through expressions, and provides the result through the return variable $?.
In this example the test command checks if 1 is less than 2 (-lt = less than):
$ test 1 -lt 2 $ echo $?0
Since the return variable was 0, the number 2 is less than 1.
In this other example it tests with "-d" if the file /usr/src is a directory:
$ test –d /usr/src$ echo $?0
The most common options of the test command are:
| Option | What It Does | Example |
| -d /directory | Checks if a file is a directory and if it exists | $ test -d /etc |
| -e file | Checks if a file exists, regardless of its type | $ test -e /etc/passwd |
| -f file | Checks if a file exists and if it is a regular file | $ test -f /etc/passwd |
| -z file | Checks if the file is empty | $ test -z /etc/groups |
| -n "$variable" | Checks if the length of a string is greater than zero | $ test -n "$BOOK" |
| -s file | Checks if a file exists and if its size is greater than zero | $ test -s /etc/passwd |
| s1 = s2 | Checks if one string is equal to another | $ test "$BOOK" = "Linux Certification" |
| s1 != s2 | Checks if a string is different from another | $ test "$BOOK" != "Linux Certification" |
| x -eq y | Checks if number x is equal to y | $ VAR=10 ; test $VAR -eq 10 |
| x -gt y | Checks if number x is greater than y | $ VAR=10 ; test $VAR -gt 9 |
| x -lt y | Checks if number x is less than y | $ VAR=10 ; test $VAR -lt 11 |
| x -ne y | Checks if number x is not equal to y | $ VAR=10 ; test $VAR -ne 11 |
| x -ge y | Checks if number x is greater than or equal to y | $ VAR=10 ; test $VAR -ge 9 |
| x -le y | Checks if number x is less than or equal to y | $ VAR=10 ; test $VAR -le 11 |
| expression -a expression | Checks if both expressions are true | $ test 10 -ge 9 -a 22 -gt 10; echo $? |
| expression -o expression | Checks if one OR expression is true | $ test 10 -ge 11 -o 22 -gt 10; echo $? |
| file1 -nt file2 | Checks if file1 was modified after file2 (newer) | $ test file1 -nt file2 |
| file1 -ot file2 | Checks if file1 was modified before file2 (older) | $ test file1 -ot file2 |
| -r file | Checks if the file has read permission | $ test -r file |
| -w file | Checks if the file has write permission | $ test -w file |
| -x file | Checks if the file has execute permission | $ test -x file |
| -O file | Checks if you are the owner of the file | $ test -O file |
Use of [ ] instead of "test"
The test command can be abbreviated with brackets [ ]. Note that there must be a space between the expression and the brackets:
$ [ 10 -ge 8 ]$ echo $?0
Operators || and &&
The operators (pipe pipe) || and && are used to check if the expression on the right returns true or false.
The operator && checks if something on its right is true, and if so, executes the command on its left.
In this example, we force the true return with the "true" command which will always return true:
$ true && echo "Deu certo"Deu certo
If we use the "false" command, which always returns false, the && operator will not execute the command on the left:
$ false && echo "Deu certo"
The operator || checks if something on its right is false, and if so, executes the command on its left.
In this example, we force the true return with the true command. In this case, the || will not execute anything.
$ true || echo "Deu certo"
Now, by forcing the false return with the false command, the || executes the echo command:
$ false || echo "Deu certo"Deu certo
The operators && and || can also be used together:
$ test 100 -gt 99 && echo "SIM" || echo "NÃO"
In this case it will return YES because 100 is greater than 99.
Flow control with if
Flow controls (if) are commands that test some alternatives and, according to the result, execute commands.
The logic of the if command is "if this is true, do this, if not, do that". See the example:
if [ $? = 0 ]; then echo ‘O comando foi completado com sucesso...’else echo ‘O comando falhou.’fi
In this example the if tests if the content of the return variable $? is 0. If positive, it executes the echo command "The command completed successfully...". If the condition is false, it executes the echo command "The command failed.".
Different from other languages, if tests a command and not a condition. Therefore, we must use the test command together with if. Usually it is written using the shortcut of brackets [ ] for the test command.
Flow control with case
The case is a smart way to compare a value against several patterns.
If a match is positive, it allows commands to be executed.
Each case is an expression that matches a pattern.
The operator ")" ends a pattern list and starts a command list.
What separates one pattern from another is ";;".
At the end of the case statement, you must end with the esac instruction (case backwards).
Example of a script that prints a different message depending on the user's UID:
#!/bin/bashID=$(id -u)case "$ID" in 0) echo "Você é o root."; echo "Parabens!" ;; 1000) echo "Você é o Uirá." ;; 100[1-9]) echo "Vocé é outro usuário"esacecho "fim";
If the ID variable value is 0, it will print a congratulations message. If it equals 1000, it prints "you are Uirá". If it is between 1001 and 1009, it prints "You are another user.
If executed with the user uira, who has UID equal to 1000:
$ ./meucase Você é o Uirá.fim
If executed as root:
$ sudo ./meucase Você é o root.Parabens!fim
The case is better than using the "if" command multiple times to compare something with various patterns.
Loops with the for command
$ for algo; do comando; comando2; done
The shell has structures to test conditions and execute certain program sequences multiple times (loop), until the tested condition is satisfied.
The three commands that enable this are for (until), while (while true), and until (while false).
The for command allows loops to be made so that one or more commands are executed until a given variable goes through all the values of a given list.
See a simple example:
$ for numero in um dois três quatro cincodoecho "Contando: $numero"done
Contando: um
Contando: dois
Contando: três
Contando: quatro
Contando: cinco
The same command can be written on a single line:
$ for numero in um dois três quatro cinco; do echo "Contando: $numero"; done
See the example:
$ ls -1 > lista_arquivos.txt
You can now use for to execute various commands for each file in the list:
$ for i in $(cat lista_arquivos.txt); do cp $i $i.backup; mv $i.backup /tmp/backup; done;
This loop assigns each line of the lista_arquivos.txt file to the $i variable.
The expression $(command) generates a list with the command result. It has the same effect as using the command within backticks: `command`.
Then it executes the commands to rename and move files until the list is complete.
Now a slightly more complex example, using for with if:
$ for i in `ls -1`; do if test -f $i; then echo “$i é um arquivo “; else echo “$i não é um arquivo”; fi ; done
Desktop não é um arquivoDocuments não é um arquivoDownloads não é um arquivoHR_PROFESSOR.sql é um arquivo
In this line, the result of the ls -1 command is placed in the variable $i; Then each line of the $i variable is tested to see if it is a file; if true, a phrase will be displayed and, if false, another phrase.
Loops with the while command
$ while [ expression ] ; do command; command; done
While continuously tests an expression, until an expression has a return variable equal to zero or true.
In this example, the variable $i gets the initial value equal to zero.
While (while) the condition of the test command represented by [ ] returns zero (true), the loop will continue to be executed.
In the loop the variable $i is incremented, until $i reaches the condition of not being less than 4:
$ i=0
$ while [ $i -lt 4 ]; do echo "conta $i" ; i=$[$i+1]; doneconta 0conta 1conta 2conta 3
While needs to have an exit condition satisfied, otherwise it will be in an infinite loop.
Loops with the until command
The until command is the opposite of the while command, but it executes something while the test is false, or with values different from zero.
Its syntax is:
until [CONDIÇÃO]do [COMANDOS]done
Example:
#!/bin/bashcounter=0until [ $counter -gt 3 ]do echo Counter: $counter ((counter++))done
When executed:
$ ./contador Counter: 0Counter: 1Counter: 2Counter: 3
The until is useful for making a script wait until a command no longer returns an error, since it is only executed if the test return is different from zero.
The zero exit code of a program usually indicates that it was executed successfully.
In this example, the until command is used to wait until the host can ping the IP 8.8.8.8. When the ping command successfully pings the host 8.8.8.8, it will return zero, causing the processing to leave the loop:
#!/bin/bash
until ping -c 1 8.8.8.8 &>/dev/null
do
echo "Esperando a rede..."
sleep 1
done
echo "A rede está no ar"
Learn much more about Linux in our online course. You can enroll here. If you already have an account, or want to create one, just log in or create your user here.
Did you like it? Share
That was just one piece. The course teaches the whole path — from your first command to exam day.