The test command in the shell is used to check if a condition is true, and it can be tested in three aspects of numeric, character, and file.
Numerical Test
-eq equalsis True
-ne Not equal tois True
-gt greater thanis True
-ge greater than or equal tois True
-lt less thanis True
-le less than or equal tois True
Example Demo:
num1=100
num2=100
if test $[num1]-eq $[num2]
Then
Echo ' Two numbers equal! ‘
Else
Echo ' Two numbers are not equal! ‘
Fi
Output Result:
Two numbers equal!
The [] in the code performs the basic arithmetic operations, such as:
#!/bin/bash
A=5
B=6
RESULT=$[A+B]# Note that there must be no spaces on both sides
echo "Result: $result"
The result is:
Result is: 11
String Test
= Equals is True
! = is not equal is true
-Z String string is true if the length is zero
-N String string is true if the length is nonzero
Example Demo:
num1= "Ru1noob"
Num2= "Runoob"
if test $num 1 = $num 2
Then
Echo ' Two strings equal! '
Else
Echo ' two strings are not equal! '
Fi
Output Result:
Two strings are not equal!
file Test
-e File name True if the file exists
-r file name True if the file exists and is readable
-W file name True if the file exists and is writable
-X file name if file exists and executable is true
-S file name True if the file exists and has at least one character
-d file name if the file exists and is true for the directory
-f filename If file exists and is normal file true
-C file name True if the file exists and is a character-specific file
-B file name True if file exists and is a block special file
Example Demo:
Cd/bin
If Test-e./bash
Then
Echo ' file already exists! '
Else
Echo ' file does not exist! '
Fi
Output Result:
File already exists!
In addition, the shell is provided with (-a), or (-O), non (!) Three logical operators are used to connect test conditions with the following precedence:"!" Highest, "-a" followed, "-O" the lowest. For example:
Cd/bin
If Test-e./notfile-o-E./bash
Then
Echo ' has at least one file present! '
Else
Echo ' Two files are not present '
Fi
Output Result:
At least one file exists!
11-shell Test command