English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The test command in Shell is used to check if a condition is true, it can perform tests on numbers, characters, and files.
Parameter | Description |
---|---|
-eq | equal then true |
-ne | not equal is true |
-gt | greater than is true |
-ge | greater than or equal to is true |
-lt | less than is true |
-le | less than or equal to is true |
num1=100 num2=100 if test $[num1] -eq $[num2] then echo 'Two numbers are equal!' else echo 'Two numbers are not equal!' fi
Output Result:
Two numbers are equal!
The [] in the code performs basic arithmetic operations, such as:
#!/bin/bash a=5 b=6 result=$[a+b] # Note that there should be no space around the equal sign echo "result is: $result"
The result is:
result is: 11
Parameter | Description |
---|---|
= | equal then true |
!== | not equal then true |
-z string | The length of the string is zero if true |
-n String | If the length of the string is not zero, it is true |
num1="ru1noob" num2="w3codebox" if test $num1 = $num2 then echo 'Two strings are equal!' else echo 'Two strings are not equal!' fi
Output Result:
Two strings are not equal!
Parameter | Description |
---|---|
-e Filename | If the file exists, it is true |
-r Filename | If the file exists and is readable, it is true |
-w Filename | If the file exists and is writable, it is true |
-x Filename | If the file exists and is executable, it is true |
-s Filename | If the file exists and has at least one character, it is true |
-d Filename | If the file exists and is a directory, it is true |
-f Filename | If the file exists and is a regular file, it is true |
-c Filename | If the file exists and is a character special file, it is true |
-b Filename | If the file exists and is a block special file, it is true |
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, Shell also provides with ( -a ) Or ( -o ) Non-(! ) three logical operators are used to connect test conditions, with their priority as: ! highest, -a Next, -o Lowest. For example:
cd /bin if test -e ./notFile -o -e ./bash then echo 'At least one file exists!' else echo 'Two files do not exist' fi
Output Result:
At least one file exists!