Introduction to if else and greater than, less than, equal logical expressions in linux shell

In linux shell programming, in most cases, you can use the test command to test the conditions. Here is a brief introduction, which is convenient for friends who need it. For
example , compare strings, judge whether the file exists and whether it is readable, etc., usually use "[ ]" to indicate a conditional test.

Note: whitespace is important here. Be sure to space the square brackets. I have wasted a lot of precious time because of missing spaces or the wrong location.

if ....; then
....
elif ....; then
....
else
....
fi
[ -f "somefile" ] : Determine whether it is a file
[ -x "/bin/ls" ] : Determine whether /bin/ls exists and has executable permissions
[ -n "$var" ] : Determine whether the $var variable has a value
[ "$a" = "$b"









Conditional selection shell scripts are generally adequate for tasks that do not contain variables and simple shell scripts. However, when performing some decision-making tasks, it is necessary to include if/then conditional judgments. Shell script programming supports such operations, including comparison operations, judging whether a file exists, etc.
The basic if conditional command options are: - eq — compares two arguments for equality (for example, if [ 2 –eq 5 ])
-ne — compares two arguments for inequality
-lt — argument 1 is less than argument 2
-le — Whether parameter 1 is less than or equal to parameter 2
-gt - whether parameter 1 is greater than parameter 2
-ge - whether parameter 1 is greater than or equal to parameter 2
-f - check whether a file exists (for example, if [ -f "filename" ])
-d - check
Almost can be implemented using these comparison operators. The -f command option is commonly used in scripts to check for the existence of a file before executing it.
Here are two examples to facilitate your understanding.
1. Determine whether the file exists
Copy code as follows:

#!/bin/sh
# Determine whether the 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" [email protected] <error.log
fi
Copy the code as follows:

#!/bin/sh
# Clear related files, And record 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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326385194&siteId=291194637