12.Shell test 命令

Shell test 命令

Shell中的 test 命令用于检查某个条件是否成立,它可以进行数值、字符和文件三个方面的测试。

数值测试

参数

说明

-eq

等于(equal)则为真

-ne

不等于(no equal)则为真

-gt

大于(greater than)则为真

-ge

大于等于(greater than or equal)则为真

-lt

小于(little than)则为真

-le

小于等于(little or equal)则为真

实例演示:

1.num1=100
2.num2=100
3.if test $[num1] -eq $[num2]
4.then
5.    echo '两个数相等!'
6.else
7.    echo '两个数不相等!'
8.fi

输出结果:

1.两个数相等!

实践

1.#!/bin/bash
2.
3.num1=1000
4.num2=1000
5.
6.if test $num1 -eq $num2
7.then
8.        echo '两个数相等!'
9.        echo $num1
10.        echo $num2
11.else
12.        echo '两个数不相等!'
13.fi

输出结果

1.[root@localhost lcr]# ./helloworld.sh 
2.两个数相等!
3.1000
4.1000

代码中的 [] 执行基本的算数运算,如:

1.#!/bin/bash
2.
3.a=5
4.b=6
5.
6.result=$[a+b] # 注意等号两边不能有空格
7.echo "result 为: $result"

结果为:

1.result 为: 11

实践

1.#!/bin/bash
2.
3.a=5
4.b=6
5.
6.result=$[a+b]
7.echo "result = $result"

输出为

1.[root@localhost lcr]# ./helloworld.sh 
2.result = 11

字符串测试

参数

说明

=

等于则为真

!=

不相等则为真

-z字符串

字符串的长度为零则为真

-n字符串

字符串的长度不为零则为真

实例演示:

1.num1="ru1noob"
2.num2="runoob"
3.if test $num1 = $num2
4.then
5.    echo '两个字符串相等!'
6.else
7.    echo '两个字符串不相等!'
8.fi

输出结果:

1.两个字符串不相等!

实践

1.#!/bin/bash
2.
3.num1="runtoone"
4.num2="runtotwo"
5.
6.if test $num1 = num2
7.then
8.        echo '两个字符串相同‘
9.else
10.        echo '两个字符串不相同’
  • 结尾要加fi

  • 引用变了要带:$

  • 中英文输入切换注意符号

修改后:

1.#!/bin/bash
2.
3.num1="run to one"
4.num2="run to two"
5.
6.if test $num1 = $num2
7.then
8.        echo '两个字符串相同!'
9.else
10.        echo '两个字符串不相同!'
11.fi

输出:

1.[root@localhost lcr]# ./helloworld.sh 
2../helloworld.sh: 第 6 行:test: 参数太多
3.两个字符串不相同!

文件测试

参数

说明

-e文件名

(exist)如果文件存在则为真

-r文件名

(read)如果文件存在且可读则为真

-w文件名

(write)如果文件存在且可写则为真

-x文件名

如果文件存在且可执行则为真

-s文件名

如果文件存在且至少有一个字符则为真

-d文件名

如果文件存在且为目录则为真

-f文件名

(file)如果文件存在且为普通文件则为真

-c 文件名

(char)如果文件存在且为字符型特殊文件则为真

-b 文件名

如果文件存在且为块特殊文件则为真

实例演示:

1.cd /bin
2.if test -e ./bash
3.then
4.    echo '文件已存在!'
5.else
6.    echo '文件不存在!'
7.fi

输出结果:

1.文件已存在!

实践

1.#!/bin/bash
2.cd
3.if test -e /home/lcr/mediawiki-1.29.0.tar.gz
4.then
5.        echo '文件存在!'
6.else
7.        echo '文件不存在!'
8.fi

输出

1.[root@localhost lcr]# ./helloworld.sh 
2.文件存在!

另外,Shell还提供了与( -a )、或( -o )、非( ! )三个逻辑操作符用于将测试条件连接起来,其优先级为:”!”最高,”-a”次之,”-o”最低。 例如:

1.cd /bin
2.if test -e ./notFile -o -e ./bash
3.then
4.    echo '有一个文件存在!'
5.else
6.    echo '两个文件都不存在'
7.fi

输出结果:

1.有一个文件存在!

Last updated

Was this helpful?