test command common usage
test command usage. Function: Check the file and compare values
1) determine the expression
if test (the expression is true)
if test! expression is false
test expressions 1 -a 2 expression both expressions are true
1 -o test Expression Expression 2 has a two expressions is true
2) determining a string
zero length string test string -n
The string length is zero test -z
String String test 1 = 2 strings are equal
test string 1! String String = 2 ranging
3) determining an integer
test integer of 1 -eq integer equal to an integer of 2
test integer of 1 -ge integer integer integer of 2
test integer of 1 -gt integer integer integer greater than 2
-le test integer of 1 2 integer smaller than an integer equal to an integer of 2
-LT-1 test integer smaller than an integer of an integer of an integer of 2 1 2
test integer of 1 -ne integer of 2 does not equal an integer of 1 2 integer
4) determine the file
test File1 -nt File2 file 1 to file new 2
test File1 -ot File2 file 1 to file 2 Old
test -b File file exists and is a block device file
test -c File file exists and is a character device file
It exists and is a directory test -d File file
test -e File file exists
The presence of test -f File is a regular file and file
test -h File file exists and is a symbolic link
test -b File file exists and is a block device file
test -L File file exists and is a symbolic link
File exists and is readable test -r File
test -s File file exists and is a socket
test -w File file exists and is writable
And the presence of test -x File executable file
Shell test single brackets [] double brackets [[]] difference
When writing Shell scripts, often do not know when writing with a conditional statement []
is [[]]
, first of all we look at their category:
[
And test
a Shell internal commands, and [[
is Shell keywords.
[
And test
it is equal.
In [[
use &&
and ||
represents a logical OR and logical AND. [
Use -a
and -o
represents a logical OR and logical AND.
[[
Support string pattern matching, using the support shell = - even when the operator is a regular expression. You can put the right string comparison as a model, not just a string, such as [[hello == hell?]], The result is true. [[]] In the matching string or wildcard, no quotation marks.
to sum up:
Use [] [...] conditional structure, instead of [...], a number of logical errors can be prevented in the script. For example, &&, ||, <and> can be present normally in the operator [[]] conditional structure, but if present in [] structure, it will be given. For example it can be used directly if [[ $a != 1 && $a != 2 ]]
, without using double parentheses, compared if [ $a -ne 1] && [ $a != 2 ]
or if [ $a -ne 1 -a $a != 2 ]
, bash the double brackets in expression as a single element, and returns an exit status code.