The article directories
-
-
- preface
- The numerical test
- String test
- File test
-
preface
The test command in the Shell is used to check whether a condition is true. It can test numeric values, characters, and files.
The numerical test
parameter | instructions |
---|---|
-eq | Equals is true |
-ne | It is true if it is not |
-gt | Greater than is true |
-ge | Greater than or equal to is true |
-lt | Less than is true |
-le | Less than or equal to true |
The instance
num1=100
num2=100
if test $[num1] -eq $[num2]
then
echo 'Two numbers are equal! '
else
echo 'Two numbers are not equal! '
fi
Copy the code
Output result:
Two numbers are equal!Copy the code
[] in the code performs basic arithmetic operations, such as:
The instance
#! /bin/bash
a=5
b=6
result=$[a+b] # Notice no Spaces on either side of the equal sign
echo "The result is:$result"
Copy the code
The result is:
The result is: 11Copy the code
String test
parameter | instructions |
---|---|
= | Equals is true |
! = | It is true if it is not equal |
Z string | A string of zero length is true |
– n strings | A string whose length is not zero is true |
The instance
num1="ru1noob"
num2="runoob"
if test $num1 = $num2
then
echo 'Two strings equal! '
else
echo 'Two strings are not equal! '
fi
Copy the code
Output result:
Two strings are not equal!Copy the code
File test
parameter | instructions |
---|---|
– e file name | True if the file exists |
The -r filename | True if the file exists and is readable |
– w filename | True if the file exists and is writable |
– x filename | True if the file exists and is executable |
The -s filename | True if the file exists and has at least one character |
– d file name | True if the file exists and is a directory |
The -f filename | True if the file exists and is a normal file |
– c file name | True if the file exists and is a character special file |
– b file name | True if the file exists and is block-special |
The instance
cd /bin
if test -e ./bash
then
echo 'File already exists! '
else
echo 'File does not exist! '
fi
Copy the code
Output result:
File already exists!Copy the code
In addition, Shell provides and (-a), or (-o), not (!) Three logical operators are used to concatenate test conditions, with precedence of:! Highest, followed by -a, and lowest by -O. Such as:
The instance
cd /bin
if test -e ./notFile -o -e ./bash
then
echo 'At least one file exists! '
else
echo 'Neither file exists'
fi
Copy the code
Output result:
At least one file exists!Copy the code