Detailed explanation of operators in linux shell programming

foreword

Operators are the basic syntax of any programming language. This article will introduce the use of commonly used operators in the shell in detail.

Classification of operators in the shell

  • arithmetic operator
  • comparison operator
  • boolean operator
  • Logical Operators

1. Arithmetic operators

Summary of commonly used arithmetic operators

operator illustrate example
+ addition expr $a + $bThe result is 3
- subtraction expr $a - $bThe result is -1
* multiplication expr $a \* $bThe result is 2
/ division expr $b / $aThe result is 2
% Take the remainder expr $b % $aThe result is 0
= assignment a=$b will assign the value of variable b to a

If () is used in the four arithmetic operations, it also needs to be escaped\( 1 + 1 \)

1. Case operation demonstration

#!/bin/bash
a=1 b=2          # 声明变量a=11和b=22
echo "a=${a} b=${b}"
echo "a + b = `expr $a + $b`"
echo "a * b = `expr $a \* $b`"
echo "a - b = `expr $a - $b`"
echo "a * b = `expr $a \* $b`"
echo "b / a = `expr $b / $a`"
echo "b % a = `expr $b % $a`"

echo -n "a == b 结果为 "
if [ $a == $b ]       # 注意变量与符号之间都要有空格
then
        echo true
else
        echo false
fi

echo -n "a != b 结果为 "
if [ $a != $b ]        # 注意变量与符号之间都要有空格
then
        echo true
else
        echo false
fi

Execute the above script and observe the output

 

When using operators to perform common script operations, the expr command can be said to be used very frequently, so it is necessary to make a detailed summary of the use of this command;

2. Detailed explanation of the expr command

expr, translated as "expression evaluation". In the shell, expr is a powerful and complex command. In addition to integer calculation, it can also combine some options to process strings, such as calculating the length of strings, comparing strings, matching strings, and extracting strings.

Requirement 1: Find the sum of two numbers

expr 1 + 1

 

Requirement 2: Find the sum of two numbers and assign it to a new variable

result=`expr 1 + 1 `

 

expr operates on strings

Calculate string length

expr length 字符串
# 例如: expr length "welcome"  返回: 7

 

intercept string

expr substr 字符串 start end
# start 截取字符串的起始位置, 从1开始
# end 截取字符串的结束位置, 包含这个位置截取
# 例如 expr substr "welcome" 1 2  返回: we

 

Get the position of the first occurrence of a character in a string

expr index 被查找字符串  需要查找的字符
# 例如 expr index "welcome" e  会返回: 1

 

Regular expression matching syntax

expr match 字符串 正则表达式
# 正则表达式默认带有^ ,  代表以什么开头
# 返回值为符合匹配字符的长度, 否则返回为0
# 例如: expr match "welcome" ".*m"  会返回: 6
# 正则表达式通配符"."代表任意一个字符
# 正则表达式通配符"*"代表签名的字符可以出现0到多次
# ".*m" 含义为匹配字符串中m前面的字符串长度 

 

Comprehensive case of string manipulation

#!/bin/bash
# 四则运算
result=`expr \( 10 + 10 \) \* 2 + 100`
echo "(10+10)*2+100=${result}"

# 计算字符串的长度
echo "welcome字符串长度=`expr length "welcome"`"

# 获取第一个字符在字符串中出现的位置
echo "welcome字符串中第一个t的位置=`expr index "welcome" e`"

# 正则表达式匹配1
echo "正则表达式match匹配查找welcome字符串中m前面任意字符的总长度=`expr match "welcome" ".*m"`"

# 正则表达式匹配2
echo "正则表达式匹配查找welcome字符串中m前面任意字符的总长度=`expr "welcome" : ".*m"`"

Run the script to observe the execution effect

 

Second, the comparison operator

In various programming languages, it is often necessary to perform various comparison operations between values ​​or strings. Regarding the shell, it also provides a relatively rich comparison operator;

1. Integer comparison operators

The commonly used comparison operators on integers are listed below, assuming variable a is 1 and variable b is 2:

operator illustrate example
-eq equals checks whether two numbers are equal, equal returns 0, otherwise returns 1. [ $a -eq $b ]returns 1.
-ne not equals detects whether two numbers are not equal, and returns true if they are not equal. [ $a -ne $b ]returns 0.
-gt greater than detects whether the number on the left is greater than the number on the right, and returns 0, otherwise 1 [ $a -gt $b ]returns 1.
-lt lower than checks whether the number on the left is smaller than the number on the right, and returns 0, otherwise 1 [ $a -lt $b ]returns 0.
-ge Greater equals detects whether the number on the left is greater than or equal to the number on the right, and returns 0, otherwise 1 [ $a -ge $b ]returns 1.
-le lower equals checks whether the number on the left is less than or equal to the number on the right, and returns 0, otherwise 1 [ $a -le $b ]returns 0.
< Check whether the number on the left is smaller than the number on the right, and return 0, otherwise 1 (($a<$b))return 0
<= Check whether the number on the left is less than or equal to the number on the right, and return 0, otherwise 1 (($a<=$b))return 0
> Check whether the number on the left is greater than the number on the right, and return 0, otherwise 1 (($a>$b))return 1
>= Check whether the number on the left is greater than or equal to the number on the right, and return 0, otherwise 1 (($a>=$b))return 1

Notice:

1) Integer comparison operators only support integers, not decimals and strings (string comparisons will be explained later), unless the value of the string is an integer number;

2) Each command has a return value. We will explain the exit status later and explain it in detail. Returning 0 means success, and returning 1 means failure

Operation case display, written in the shell as follows

#!/bin/bash
a=11 b=22
echo "a=${a} b=${b}"
if [ $a -eq $b ]
then
   echo "$a -eq $b : a 等于 b"
else
   echo "$a -eq $b: a 不等于 b"
fi
if [ $a -ne $b ]
then
   echo "$a -ne $b: a 不等于 b"
else
   echo "$a -ne $b : a 等于 b"
fi
if [ $a -gt $b ]
then
   echo "$a -gt $b: a 大于 b"
else
   echo "$a -gt $b: a 不大于 b"
fi
if [ $a -lt $b ]
then
   echo "$a -lt $b: a 小于 b"
else
   echo "$a -lt $b: a 不小于 b"
fi
if [ $a -ge $b ]
then
   echo "$a -ge $b: a 大于或等于 b"
else
   echo "$a -ge $b: a 小于 b"
fi
if [ $a -le $b ]
then
   echo "$a -le $b: a 小于或等于 b"
else
   echo "$a -le $b: a 大于 b"
fi

if (($a > $b))
then
   echo "$a > $b: a 大于 b"
else
   echo "$a > $b: a 不大于 b"
fi
if (($a < $b))
then
   echo "$a < $b: a 小于 b"
else
   echo "$a < $b: a 不小于 b"
fi
if (($a >= $b))
then
   echo "$a >= $b: a 大于或等于 b"
else
   echo "$a >= $b: a 小于 b"
fi
if (($a <= $b))
then
   echo "$a <= $b: a 小于或等于 b"
else
   echo "$a <= $b: a 大于 b"
fi

Execute the above script and observe the effect

 

2. String comparison operators

Can compare 2 variables, the type of variable can be number (integer, decimal) and string

Commonly used string operators are listed below, assuming variable a is "abc" and variable b is "efg":

String comparison can be done using [[]]and []2 ways

operator illustrate example
== or = equal. Used to compare two strings or numbers, return 0 if they are the same. can use= [ $a == $b ]return 1 [ $a = $b ]return 1 [[ $a == $b ]]return 1 [[ $a = $b ]]return 1
!= not equal. Used to compare two strings or numbers, and return 0 if they are not the same. [ $a != $b ]return 0 [[ $a != $b ]]return 0
< Less than, used to compare two strings or numbers, less than return 0, otherwise return 1 [ $a \< $b ]return 0 [[ $a < $b ]]return 0
> Greater than, used to compare two strings or numbers, greater than return 0, otherwise return 1 [ $a \> $b ]return 1 [[ $a > $b ]]return 1
-z Check whether the length of the string is 0, and return true if it is 0. [ -z $a ] returns 1.
-n Check whether the length of the string is not 0, and return true if it is not 0. [ -n "$a" ] returns 0.
$ Check whether the string is not empty, return 0 if it is not empty, otherwise return 1. [ $a ] returns 0.

String comparisons <=without[[ "a" < "b" && "a" = "b" ]]

String operator case demonstration, written in the shell as follows

#!/bin/bash

a="welcome" b="wednesday " c=1 d=2  #初始变量赋值
echo "a=${a},b=${b},c=${c},d=${d}"

if [ $a = $b ]
then
   echo "$a = $b : a 等于 b"
else
   echo "$a = $b: a 不等于 b"
fi

if [ $a != $b ]
then
   echo "$a != $b : a 不等于 b"
else
   echo "$a != $b: a 等于 b"
fi

if [[ $a > $b ]]
then
   echo "$a > $b : a 大于 b"
else
   echo "$a > $b: a 不大于 b"
fi

if [ $a \> $b ]
then
   echo "$a > $b : a 大于 b"
else
   echo "$a > $b: a 不大于 b"
fi

if [[ $c > $d ]]
then
   echo "$c > $d : c 大于 d"
else
   echo "$c > $d: c 不大于 d"
fi

if [ -z $a ]
then
   echo "-z $a : 字符串长度为 0"
else
   echo "-z $a : 字符串长度不为 0"
fi

if [ -n "$a" ]
then
   echo "-n $a : 字符串长度不为 0"
else
   echo "-n $a : 字符串长度为 0"
fi

if [ $a ]
then
   echo "$a : 字符串不为空"
else
   echo "$a : 字符串为空"
fi

Execute the above script and observe the output effect

 

3. Boolean operators

Boolean operators, in simple terms, compare whether two numbers or strings are logically equal or unequal, or true or false, and the result is often only one true or false; the following lists the common operation instructions about Boolean operators;

operator illustrate example
! Not operation, negation, return false if the expression is true, otherwise return true. [ ! false ]returns true.
-o or or operation, if an expression is true, it returns true. [ 表达式1 -o 表达式2 ]returns true.
-a and and operation, both expressions are true to return true. [ 表达式1 -a 表达式2 ]returns false.

Note that Boolean operators are only []valid if placed in

In the future, Boolean operators and test commands are often used to test connection conditions.

Let's look at a case demonstration about Boolean operators, with the following shell

#!/bin/bash
a=8 b=22  #变量赋值 

if [ $a -lt 2 -a $b -gt 10 ]
then
   echo "$a 小于 2 且 $b 大于 10 : 返回 true"
else
   echo "$a 小于 2 且 $b 大于 10 : 返回 false"  # $b -gt 10不成立, 输出这个表达式
fi

if [ $a -lt 10 -o $b -gt 10 ]
then
   echo "$a 小于 10 或 $b 大于 10 : 返回 true"  # $a -lt 10 成立, 输出这个表达式
else
   echo "$a 小于 10 或 $b 大于 10 : 返回 false"
fi

if [ ! $a -gt $b ]
then
   echo "$a 大于 $b 取反 : 返回 true"
else
   echo "$a 大于 $b 取反 : 返回 false"   # $a -gt $b 为true , 取反为false, 输出这个表达式
fi

Execute the above script and observe the output effect

 

4. Logical operators

basic grammar

operator illustrate example
&& Logical AND [[ 表达式1 && 表达式2 ]]returns false
|| Logical OR [[ 表达式1 || 表达式2 ]]return true

Notice:

1. Operators using and&& must be placed in or to be valid, otherwise an error will be reported;||[[]](())

2、-a-oThe operators of and must be placed []in to be valid or in the test command

3.! Can be used in [], [[]]but not in (())

Logical operators are relatively simple, let’s look directly at a shell command

#!/bin/bash

a=7 b=20 #变量赋值

if [[ $a -lt 10 && $b -gt 10 ]]
then
   echo "返回 true" 
else
   echo "返回 false"  # $b -gt 10 不成立, 输出false
fi

if [[ $a -lt 10 || $b -gt 10 ]]
then
   echo "返回 true"   # $a -lt 10 成立,  输出true
else
   echo "返回 false"  
fi

Run the above shell to observe the execution effect

 

Five, file test operator

Finally, let’s introduce an operator that is also used very frequently in shell programming, the file test operator,

definition

File test operators are used to test various attributes of files.

There are many scenarios related to file testing. For example, when you cd to a certain directory and want to operate on a certain file in the directory, in order to ensure the robustness of the script, you need to do some pre-processing on the directory and the file. For verification operations, operators related to file testing are used;

Commonly used file test attribute detection is described as follows:

operator illustrate example
-b file Checks if the file is a block device file, and returns true if it is. [ -b $file ] returns false.
-c file 检测文件是否是字符设备文件,如果是,则返回 true。 [ -c $file ] 返回 false。
==-d file== directory, 检测文件是否是目录,如果是,则返回 true。 [ -d $file ] 返回 false。
==-f file== file, 检测文件是否是普通文件(既不是目录,也不是设备文件) ,如果是,则返回 true。 [ -f $file ] 返回 true。
-g file 检测文件是否设置了 SGID 位,如果是,则返回 true。 [ -g $file ] 返回 false。
-k file 检测文件是否设置了粘着位(Sticky Bit),如果是, 则返回 true。 [ -k $file ] 返回 false。
-p file 检测文件是否是有名管道,如果是,则返回 true。 [ -p $file ] 返回 false。
-u file 检测文件是否设置了 SUID 位,如果是,则返回 true。 [ -u $file ] 返回 false。
==-r file== read,检测文件是否可读,如果是,则返回 true。 [ -r $file ] 返回 true。
==-w file== write,检测文件是否可写,如果是,则返回 true。 [ -w $file ] 返回 true。
==-x file== execute, 检测文件是否可执行,如果是,则返回 true。 [ -x $file ] 返回 true。
==-s file== size, 检测文件是否为空(文件大小是否大于0) ,不为空返回 true。 [ -s $file ] 返回 true。
==-e file== exists, 检测文件(包括目录)是否存在,如果是, 则返回 true。 [ -e $file ] 返回 true。
file1 -nt file2 new than(nt), file1是否比file2新 [ file1 -nt file2 ]
file1 -ot file2 old than(ot), file1是否比file2旧 [ file1 -ot file2 ]

补充其他检查符:

  • -S: 判断某文件是否 socket;
  • -L: link, 检测文件是否存在并且是一个符号链接;

语法:

[ options 文件路径字符串]

[[ options 文件路径字符串 ]]

来看一个具体的关于文件测试运算符的shell示例,在当前目录下有file1.sh 和 file2.sh

 

shell 脚本如下:

#!/bin/bash

file="/usr/shells/file1.sh"
if [ -w $file ]
then
   echo "文件可写"
else
   echo "文件不可写"
fi
if [ -r $file ]
then
   echo "文件可读"
else
   echo "文件不可读"
fi
if [ -x $file ]
then
   echo "文件可执行"
else
   echo "文件不可执行"
fi
if [ -f $file ]
then
   echo "文件是普通文件"
else
   echo "文件是特殊文件"
fi
if [ -s $file ]
then
   echo "文件不是空"
else
   echo "文件是空"
fi
if [ -e $file ]
then
   echo "文件存在"
else
   echo "文件不存在"
fi
if [ -d $file ]
then
   echo "文件是目录"
else
   echo "文件不是目录"
fi

file2="/usr/shells/operation2.sh"
if [ file -nt file2 ]
then
   echo "operation1.sh文件比operation2.sh文件新"
else
   echo "operation1.sh文件不比operation2.sh文件新"
fi

运行上面的脚本,观察执行效果

 

效果说明

  • operation1.sh文件不可执行, 因为没有可执行权限

查看file1.sh文件权限

 给file1.sh 添加执行权限,再次执行时效果如下

 

六、补充知识点

[[]][] 的区别,在shell编程中,这是很多初学者容易混淆的两个表达符

区别1: word splitting的发生

  • [[]] 不会有word splitting发生
  • [] 会有word splitting发生

word splitting介绍

会将含有空格字符串进行分拆分割后比较

 

 

区别2: 转义字符

  • [[]]< 不需要转义, 格式为 [[ 字符串1 < 字符串2 ]];
  • [] 需要对 <,>等 转义 , 格式为 [ 字符串1 \< 字符串2 ];

案例演示

 

 

本篇结合案例操作,详细介绍了shell中的常见的操作运算符的使用,希望对您有用哦,最后感谢观看!

Guess you like

Origin blog.csdn.net/congge_study/article/details/126813760