For example, to compare strings, to determine whether a file exists and whether it is readable, and so on, usually use "[]" to represent the conditional test.
Note: The space here is very important. To ensure that the square brackets are blank. I have been because of the lack of space or the wrong location, and waste a lot of precious time.
If ...; Then
....
Elif ...; Then
....
Else
....
Fi
[f "Somefile"]: To determine whether a file
[-X "/bin/ls"]: Determine if/bin/ls exists and has executable permissions
[-N ' $var]: Determine if the $var variable has a value
["$a" = "$b"]: Determine if $a and $b are equal
-r file user readable as True
-W file user can write as true
-X file user can execute as true
-F file is true for regular files
-D file is true for directory
-C file is true for character special files
-B file is a block special file is True
-S file file non-0 o'clock is true
-T file True when the device specified by the file descriptor (default is 1) is a terminal
Shell scripts with conditional selection are generally competent for simple shell scripts that do not contain variables. However, in the implementation of a number of decision-making tasks, it is necessary to include the if/then of the conditional judgment. Shell scripting supports such operations, including comparing operations, determining whether a file exists, and so on.
The basic if Condition command options are:-eq-compares two arguments for equality (for example, if [2–eq 5])
-ne-compare two arguments for unequal
-lt-parameter 1 is less than parameter 2
-le-parameter 1 is less than or equal to parameter 2
-gt-parameter 1 is greater than parameter 2
-ge-parameter 1 is greater than or equal to parameter 2
-f-Check if a file exists (for example, if [-F "filename"])
D-Check if the directory exists
Almost all judgements can be implemented using these comparison operators. The common-f command option in a script checks to see if it exists before executing a file.
Here are two examples to facilitate your understanding.
1, to determine whether the existence of documents
Copy Code code as follows:
#!/bin/sh
# to determine if a file exists
# link:www.jb51.net
# DATE:2013/2/27
Yaccess= ' date-d yesterday +%y%m%d '
File= "Access_$yaccess.log.tgz"
Cd/data/nginx/logs
If [f "$FILE"];then
echo "OK"
Else
echo "Error $FILE" > Error.log
Mail-s "$FILE backup fail" Test123@jb51.net <error.log
Fi
Copy Code code as follows:
#!/bin/sh
# Purge related files and log logs by time period
# link:www.jb51.net
# DATE:2013/2/27
#
Dir=/data/img_cache
day= ' date + '%y-%m-%d%h:%m '
num= ' ls $DIR |wc-l '
Dirname= ' ls $DIR | grep leveldb | Head-n 1 | awk ' {print $NF} '
if [[$NUM-gt 3]];then
RM-RF $DIR/$DIRNAME
echo "---------$DAY----($DIR)-----------------------" >>/tmp/img_cache.log
echo "$DIRNAME Deleted successful" >>/tmp/img_cache.log
Fi