三.变量的运算

目录

3.1 基本语法

3.2 算术运算符

3.3 字符串运算符

3.4 文件测试运算符

3.5 关系运算符

3.6 布尔运算符

3.7 逻辑运算符

3.8 运算表达式


Shell 和其他编程语言一样,支持多种运算符,包括:

算数运算符

关系运算符

布尔运算符

字符串运算符

文件测试运算符

原生bash不支持简单的数学运算,但是可以通过其他命令来实现,例如 awk 和 expr,expr最常用。

expr 是一款表达式计算工具,使用它能完成表达式的求值操作。

例如,两个数相加(注意使用的是反引号 ` 而不是单引号 '):

[root@kittod ~]# expr 2 + 2
4

两点注意:

1. 表达式和运算符之间要有空格,例如 2+2 是不对的,必须写成 2 + 2,这与我们熟悉的大多数编程语言不一样。

2. 完整的表达式要被 包含,注意这个字符不是常用的单引号,在 Esc 键下边。

为了能够正确处理Shell程序运行过程中遇到的各种情况,Linux Shell提供了一组测试运算符。通过这些运算符,Shell程序能够判断某种或者几个条件是否成立。条件测试在各种流程控制语句,例如判断语句和循环语句中发挥了重要的作用,所以,了解和掌握这些条件测试是非常重要的。

3.1 基本语法

在shell程序中,用户可以使用测试语句来测试指定的条件表达式的条件的真或假。当指定的条件为真时,整个条件测试的返回值为0;反之,如果指定的条件为假,则条件测试语句的返回值为非0值。

3.2 算术运算符

下表列出了常用的算术运算符,假定变量 a 为 10,变量 b 为 20:

注意:条件表达式要放在方括号之间,并且要有空格,例如: [$a==$b] 是错误的,必须写成 [ $a == $b ]

算术运算符实例如下:

[root@kittod ~]# cat suanshu.sh
#!/bin/bash
a=10
b=20
echo "a是$a,b是$b"

val=`expr $a + $b`
echo "a + b : $val"

val=`expr $a - $b`
echo "a - b : $val"

val=`expr $a \* $b`
echo "a * b : $val"

val=`expr $b / $a`
echo "b / a : $val"

val=`expr $b % $a`
echo "b % a : $val"

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

[root@kittod ~]# bash suanshu.sh
a是10,b是20
a + b : 30
a - b : -10
a * b : 200
b / a : 2
b % a : 0
a 不等于 b

注意:

乘号(*)前边必须加反斜杠()才能实现乘法运算;

3.3 字符串运算符

下表列出了常用的字符串运算符,假定变量 a 为 "abc",变量 b 为 "efg":

字符串运算符实例如下:

[root@kittod ~]# cat zifuchuan.sh
#!/bin/bash

a="abc"
b="efg"

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 [ -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
[root@kittod ~]# bash zifuchuan.sh
abc = efg: a 不等于 b
abc != efg : a 不等于 b
-z abc : 字符串长度不为 0
-n abc : 字符串长度不为 0
abc : 字符串不为空

①test示例

[root@kittod ~]# test -n abc;echo $?
0
[root@kittod ~]# test -n "";echo $?
1
[root@kittod ~]# test -n " ";echo $?
0
[root@kittod ~]# test -z '';echo $?
0
[root@kittod ~]# test -z abc;echo $?
1
[root@kittod ~]# test -z ' ';echo $?
1
[root@kittod ~]# test abc = abcd ;echo $? #注意等号两边需要有空格
1
[root@kittod ~]# test abc=abcd ;echo $?
0

test -n 判断字符串是否是非空

test -z 判断字符串是否是空

②[]示例

[root@kittod ~]# [ -n '' ];echo $?
1
[root@kittod ~]# [ -n ' ' ];echo $?
0
[root@kittod ~]# [ -z '' ];echo $?
0
[root@kittod ~]# [ abc=abcd ];echo $?
0
[root@kittod ~]# [ abc = abcd ];echo $? #注意等号两边需要有空格
1

③[[]]示例

[root@kittod ~]# [[ -n abc ]];echo $?
0
[root@kittod ~]# [[ -n ' ' ]];echo $?
0
[root@kittod ~]# [[ -n '' ]];echo $?
1
[root@kittod ~]# [[ abc=acd ]] ;echo $?
0
[root@kittod ~]# [[ abc = acd ]] ;echo $? #注意等号两边需要有空格
1

注意:测试对象是变量时,变量需要加引号

[root@kittod ~]# test -n $name;echo $?
0
[root@kittod ~]# test -n "$name";echo $?
1
[root@kittod ~]# [ -n $name ];echo $?
0
[root@kittod ~]# [ -n "$name" ];echo $?
1

3.4 文件测试运算符

文件测试运算符用于检测 Unix 文件的各种属性。

属性检测描述如下:

其他检查符:

-S: 判断某文件是否 socket。

-L: 检测文件是否存在并且是一个符号链接。

测试文件的读、写、执行等属性,不光是根据文件属性rwx的标识来判断,还要看当前执行测试的用户是否真的可以按照对应的权限操作文件。

①test示例:

[root@kittod ~]# test -f file;echo $?
1
[root@kittod ~]# touch file
[root@kittod ~]# test -f file;echo $?
0
[root@kittod ~]# test -f file1;echo $?
1
[root@kittod ~]# test -x file;echo $?
1
[root@kittod ~]# ll
total 4
-rw-------. 1 root root 1263 Dec 16 19:11 anaconda-ks.cfg
-rw-r--r--. 1 root root 0 Apr 25 22:14 file
[root@kittod ~]# chmod +x file
[root@kittod ~]# test -x file;echo $?
0

②[]示例(注意测试表达式和方括号两边需要有空格)

[root@kittod ~]# [ -f file ];echo $?
0
[root@kittod ~]# [ -f file1 ];echo $?
1
[root@kittod ~]# [ -w file1 ];echo $?
1
[root@kittod ~]# ll
total 4
-rw-------. 1 root root 1263 Dec 16 19:11 anaconda-ks.cfg
-rwxr-xr-x. 1 root root 0 Apr 25 22:14 file
[root@kittod ~]# [ -w file ];echo $?
0

③[[]]示例(注意测试表达式和[[]]两边需要有空格)

[root@localhost test3]# ll
total 0
-rw-r--r--. 1 root root 0 Feb 20 10:35 file
[root@localhost test3]# [[ -f file ]];echo $?
0
[root@localhost test3]# [[ -f file1 ]];echo $?
1
[root@localhost test3]# [[ -x file1 ]];echo $?
1

注意:如果测试的文件路径是用变量来代替,变量一定要加引号

[root@localhost test3]# echo $filepath 该变量值为空
[root@localhost test3]# test -f $filepath;echo $? 
0
[root@localhost test3]# test -f "$filepath";echo $?
1

练习1:让用户输入一个文件名,并做如下判断:

变量 file 表示文件 /test.sh,它的大小为 100 字节,具有 rwx 权限。下面的代码,将检测该文件的各种属性:

[root@kittod ~]# touch /test.sh
[root@kittod ~]# cat file.sh
then
        echo "文件可读"
else
        echo "文件不可读"
fi

if [ -w $file ]
then
        echo "文件可写"
else
        echo "文件不可写"
fi

if [ -x $file ]
then
        echo "文件可执行"
else
        echo "文件不可执行"
fi

if [ -f $file ]
then
        echo "文件为普通文件"
else
        echo "文件为特殊文件"
fi

if [ -d $file ]
then
        echo "文件是目录"
else
        echo "文件不是目录"
fi

if [ -s $file ]
then
        echo "文件不为空"
else
        echo "文件为空" 
fi


if [ -e $file ]
then
        echo "文件存在"
else
        echo "文件不存在"
fi

[root@kittod ~]# bash file.sh
文件可读
文件可写
文件不可执行
文件为普通文件
文件不是目录
文件为空
文件存在

练习2:让用户输入一个文件名,并做如下判断:

(1)如果用户输入的文件为空时显示:you must input a filename,并中断程序;

(2)如果用户输入的文件不存在时,显示the file do not exist,并中断程序;

(3)如果文件存在,判断该文件的文件类型和执行者对该文件所拥有的权限。

说明:由于root在很多权限的限制上面都是无效的,所以使用root执行这个脚本时,常常会发现与ls -l的结果不相同。所以建议使用一般用户来执行这个脚本。

read -p "input a filename:" filename
test -z $filename && echo "you must input a filename" && exit 0
test ! -e $filename && echo "the file $filename do not exist" && exit 0
test -f $filename && filetype="regulare file"
test -d $filename && filetype="directory"
test -r $filename && perm="readable"
test -w $filename && perm="$perm writable"
test -x $filename && perm="$perm executable"
echo "the $filename is a $filetype"
echo "and the permissons are: $perm"

3.5 关系运算符

关系运算符只支持数字,不支持字符串,除非字符串的值是数字。

下表列出了常用的关系运算符,假定变量 a 为 10,变量 b 为 20:

注意:

=和!=也可在[]中作比较时使用,在[]中也可使用>和<符号,但需要使用反斜线转义,有时不转译虽然语法不会报错,但是结果可能会不对;

在[[]]中也可使用包含-gt和-lt的符号,不建议使用;

比较符号两端也要有空格。

关系运算符实例如下:

[root@kittod ~]# cat guanxi.sh
#!/bin/bash
a=10
b=20
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
[root@kittod ~]# bash guanxi.sh
10 -eq 20: a 不等于 b
10 -ne 20: a 不等于 b
10 -gt 20: a 不大于 b
10 -lt 20: a 小于 b
10 -ge 20: a 小于 b
10 -le 20: a 小于或等于 b

①test示例

[root@kittod ~]# test 2 -eq 3;echo $?
1
[root@kittod ~]# test 2 -eq 2;echo $?
0

②[]示例

[root@kittod ~]# [ 2 -ne 3 ];echo $?
0
[root@kittod ~]# [ 2 -ne 2 ];echo $?
1

③[[]]示例

[root@kittod ~]# [[ 2 != 3 ]];echo $?
0
[root@kittod ~]# [[ 2 != 2 ]];echo $?
1
[root@kittod ~]# [[ 2!=2 ]];echo $? 未写空格,导致出错
0

④(())示例

[root@kittod ~]# (( 2!=3 ));echo $?
0
[root@kittod ~]# ((2!=3));echo $?
0
[root@kittod ~]# ((2=3));echo $?
-bash: ((: 2=3: attempted assignment to non-variable (error token is
"=3")
1
[root@kittod ~]# ((2==3));echo $?
1
[root@kittod ~]# ((2>3));echo $?
1
[root@kittod ~]# ((2<3));echo $?
0

3.6 布尔运算符

下表列出了常用的布尔运算符,假定变量 a 为 10,变量 b 为 20:

布尔运算符实例如下:

[root@kittod ~]# cat bool.sh
#!/bin/bash
a=10
b=20
if [ $a != $b ]
then
  echo "$a != $b : a 不等于 b"
else
  echo "$a == $b: a 等于 b"
fi

if [ $a -lt 100 -a $b -gt 15 ]
then
  echo "$a 小于 100 且 $b 大于 15 : 返回 true"
else
  echo "$a 小于 100 且 $b 大于 15 : 返回 false"
fi

if [ $a -lt 100 -o $b -gt 100 ]
then
  echo "$a 小于 100 或 $b 大于 100 : 返回 true"
else
  echo "$a 小于 100 或 $b 大于 100 : 返回 false"
fi

if [ $a -lt 5 -o $b -gt 100 ]
then
  echo "$a 小于 5 或 $b 大于 100 : 返回 true"
else
  echo "$a 小于 5 或 $b 大于 100 : 返回 false"
fi

[root@kittod ~]# bash bool.sh
10 != 20 : a 不等于 b
10 小于 100 且 20 大于 15 : 返回 true
10 小于 100 或 20 大于 100 : 返回 true
10 小于 5 或 20 大于 100 : 返回 false

① []示例

[root@kittod ~]# touch ceshi
[root@kittod ~]# touch file
[root@kittod ~]# ll
total 0
-rw-r--r--. 1 root root 0 Apr 26 15:42 ceshi
-rw-r--r--. 1 root root 0 Apr 26 15:42 file
[root@kittod ~]# [ -f ceshi -a -f file ];echo $?
0
[root@kittod ~]# [ -e ceshi -a -f file ];echo $?
0
[root@kittod ~]# [ -f ceshi -o -f file ];echo $?
0
[root@kittod ~]# [ -f ceshi ];echo $?
0
[root@kittod ~]# ! [ -f ceshi ];echo $?
1
[root@kittod ~]# ll
total 4
-rw-------. 1 root root 1263 Dec 16 19:11 anaconda-ks.cfg
-rwxr-xr-x. 1 root root 0 Apr 25 22:14 file
[root@kittod ~]# [ ! -f ceshi ];echo $?
1

3.7 逻辑运算符

以下介绍 Shell 的逻辑运算符,假定变量 a 为 10,变量 b 为 20:

逻辑运算符实例如下:

[root@kittod ~]# cat luoji.sh
#!/bin/bash
a=10
b=20

if [[ $a -lt 100 && $b -gt 100 ]]
then
  echo "返回 true"
else
  echo "返回 false"
fi

if [[ $a -lt 100 || $b -gt 100 ]]
then
  echo "返回 true"
else
  echo "返回 false"
fi

[root@kittod ~]# bash luoji.sh
返回 false
返回 true

①test示例

[root@kittod ~]# ll
total 0
-rw-r--r--. 1 root root 0 Apr 26 15:42 ceshi
-rw-r--r--. 1 root root 0 Apr 26 15:42 file
[root@kittod ~]# test -f file && echo 1 || echo 0
1
[root@kittod ~]# test -f file1 && echo 1 || echo 0
0
[root@kittod ~]# ! test -f file;echo $?
1
注:命令1 && 命令2,如果命令1执行不成功,则命令2不执行。
命令3 || 命令4,如果命令3成功,不执行命令4;如果命令3不成功,则执行命令4

②[]示例

[root@kittod ~]# [ -f ceshi && -f file ];echo $?
-bash: [: missing `]'
2
[root@kittod ~]# [ -f ceshi || -f file ];echo $?
-bash: [: missing `]'
-bash: -f: command not found
127
[root@kittod ~]# [ -f file ] && [ -f ceshi ];echo $?
0
[root@kittod ~]# [ -f file ] || [ -f ceshi ];echo $?
0
[root@kittod ~]# [ -f file ] || [ -d ceshi ];echo $?
0
[root@kittod ~]# [ -f file1 ] || [ -d ceshi ];echo $?
1

③[[]]示例

[root@kittod ~]# touch file
[root@kittod ~]# touch ceshi
[root@kittod ~]# [[ -f file && -f ceshi ]];echo $?
0
[root@kittod ~]# [[ -f file || -f ceshi ]];echo $?
0
[root@kittod ~]# [[ -f file && -d ceshi ]];echo $?
1

④(())示例

[root@kittod ~]# ((2>3&&3>4));echo $?
1
[root@kittod ~]# ((2<3&&3<4));echo $?
0

实验1:通过read传入一个数字,如果传入的数字等于1,就打印1;如果等于2,就打印2,如果不等于1也不等于2,就提示输入不对,然后退出程序。

[root@kittod ~]# cat 1.sh
read -p "please input a number:" num
[ "$num" -eq 1 ] && {
  echo 1
  exit 0
}

[ "$num" -eq 2 ] && {
  echo 2
  exit 0
}

[ "$num" -ne 1 -a "$num" -ne 2 ] && {
  echo error
  exit 0
}

[root@kittod ~]# bash 1.sh
please input a number:1
1
[root@kittod ~]# bash 1.sh
please input a number:2
2
[root@kittod ~]# bash 1.sh
please input a number:3
error

实验2:通过read读入两个整数,并比较他们的大小

[root@kittod ~]# cat 2.sh
#!/bin/bash
read -p "please input two number:" a b
[ -z "$a" -o -z "$b" ] && {
  echo "please input 'two' number"
  exit 1
}

expr $a + 10 &>/dev/null
return_a=$?
expr $b + 10 &>/dev/null
return_b=$?

[ "$return_a" -eq 0 -a "$return_b" -eq 0 ] || {
  echo "please input two 'number'"
  exit 2
}

[ "$a" -lt "$b" ] && {
  echo "$a < $b"
  exit 0
}

[ "$a" -eq "$b" ] && {
  echo "$a = $b"
  exit 0
}

[ "$a" -gt "$b" ] && {
  echo "$a > $b"
  exit 0
}

[root@kittod ~]# bash 2.sh
please input two number:0 0
0 = 0
[root@kittod ~]# bash 2.sh
please input two number:0 1
0 < 1
[root@kittod ~]# bash 2.sh
please input two number:1 0
1 > 0
[root@kittod ~]# bash 2.sh
please input two number:0
please input 'two' number
[root@kittod ~]# bash 2.sh
please input two number:1 2
1 < 2
[root@kittod ~]# bash 2.sh
please input two number:a b
please input two 'number'

实验3:假设执行一个可以携带参数的script,执行该脚本后屏幕会显示如下的数据:程序的文件名;共有几个参数;若参数的个数小于2个则告知用户参数数量太少;全部的参数内容;第一个参数;第二个参数。

[root@kittod ~]# cat 3.sh
#!/bin/bash
echo "the script name is $0"

echo "the parameter number is $#"

[ "$#" -lt 2 ] && echo "the number of parameter is less than 2." && exit 0
echo "your whole parameter is '$@'"
echo "the 1st parameter is $1"
echo "the 2nd parameter is $2"

[root@kittod ~]# bash 3.sh
the script name is 3.sh
the parameter number is 0
the number of parameter is less than 2.

[root@kittod ~]# bash 3.sh 1
the script name is 3.sh
the parameter number is 1
the number of parameter is less than 2.

[root@kittod ~]# bash 3.sh 1 2
the script name is 3.sh
the parameter number is 2
your whole parameter is '1 2'
the 1st parameter is 1
the 2nd parameter is 2

[root@kittod ~]# bash 3.sh 1 2 3
the script name is 3.sh
the parameter number is 3
your whole parameter is '1 2 3'
the 1st parameter is 1
the 2nd parameter is 2

在方括号内的每个组件都需要由空格键来分隔(特别注意中括号的两端需要有空格符来分隔);在方括号内的变量,最好都要以双引号括起;在方括号内的常量最好都以单或双引号括起来。(中括号的使用方法与test几乎一模一样)

特殊条件测试表达式案例:

[ 条件1 ] && {
 命令1
 命令2
 命令3
}

[[ 条件1 ]] && {
 命令1
 命令2
 命令3
}

test 条件1 && {
 命令1
 命令2
 命令3
}

if [ 条件1 ]
then
 命令1
 命令2
 命令3
fi

3.8 运算表达式

示例:截取字符串

[root@localhost ~]# str1="hello world"

#返回变量长度
[root@localhost ~]# echo ${#str1}
11

#变量截取
#指定起始位置,一直到结束
[root@localhost ~]# echo ${str1:1}
ello world

#指定长度,不指定起始位置默认从开头开始
[root@localhost ~]# echo ${str1::3}
hel

#指定起始位置和长度
[root@localhost ~]# echo ${str1:1:3}
ell

#从右边第几个字符开始,及字符的个数
[root@localhost ~]# echo ${str1:0-1:1}
d

#输出右边的几个字符
[root@localhost ~]# echo ${str1:0-5}
world
[root@localhost ~]# echo ${str1: -5}
world

#提取完整字符串
[root@localhost ~]# echo ${str1:-5}
hello world

示例:删除字符串

#获取后缀名tar.gz
[root@localhost ~]# filename=testfile.tar.gz
[root@localhost ~]# file=${filename#*.}
[root@localhost ~]# echo $file
tar.gz

#获取后缀名.gz
[root@localhost ~]# filename=testfile.tar.gz
[root@localhost ~]# file=${filename##*.}
[root@localhost ~]# echo $file
gz

#截取testfile.tar
[root@localhost ~]# filename=testfile.tar.gz
[root@localhost ~]# file=${filename%.*}
[root@localhost ~]# echo $file
testfile.tar

#截取testfile
[root@localhost ~]# filename=testfile.tar.gz
[root@localhost ~]# file=${filename%%.*}
[root@localhost ~]# echo $file
testfile
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值