How to use the test command of Shell
Today, I would like to share with you the relevant knowledge points about how to use Shell's test command. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look.
The test command in Shell is used to check whether a condition is true, and it can be tested in terms of values, characters, and files.
Numerical test parameters show that-eq equals to true-ne is not equal to true-gt greater than or equal to true-ge greater than or equal to true-lt less than or equal to true-le less than or equal to true
Example demonstration:
Num1=100num2=100if test $[num1]-eq $[num2] then echo 'two equal numbers!' Else echo 'two numbers are not equal!' Fi
Output result:
The two numbers are equal!
[] in the code performs basic arithmetic operations, such as:
#! / bin/basha=5b=6result=$ [aqb] # Note that there can be no spaces on both sides of the equal sign echo "result is: $result"
The result is:
Result is: 11 string test parameter description = equal to true! = unequal, true-z string length is zero, true-n string length is not zero
Example demonstration:
Num1= "ru1noob" num2= "runoob" if test $num1= $num2then echo 'two strings equal!' else echo 'two strings are not equal!' fi
Output result:
Two strings are not equal! The file test parameter states that the-e file name is true if the file exists-r file name if the file exists and is readable, true-w file name if the file exists and writable, true-x file name if the file exists and executable, true-s file name if the file exists and at least one character is true-d file name if the file exists and is a directory True-f file name is true if the file exists and is a normal file-c file name is true if the file exists and is a character-type special file-b file name is true if the file exists and is a block special file
Example demonstration:
Cd / binif test-e. / bashthen echo 'file already exists!' else echo 'file does not exist!'
Fi output result:
The file already exists!
In addition, Shell provides three logical operators with (- a), or (- o) and non (!) to connect test conditions, with a priority of: "!" The highest, the second is "- a" and the lowest is "- o". For example:
Cd / binif test-e. / notFile-o-e. / bashthen echo'at least one file exists! 'else echo' neither file exists'fi'
Output result:
At least one file exists! These are all the contents of this article entitled "how to use Shell's test commands". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.