shell 编程 (10)test

test命令用于检查某条件是否成立,适用于数值、字符串、文件。

数值:

-eq: 等于为true

-ne: 不等于为true

-gt: 大于为true

-lt: 小于为true

-ge: 大于等于为true

-le: 小于等于为true

[]中执行基本算述运算

字符串:

=: 等于为true

!=: 不等于为true

-n: 不为0为true

-z: 为0为true

文件:

-e: 存在

-r: 可读

-w: 可写

-x: 可执行

-s: 至少有一个字符,即不为空

-d: 目录

-f: 普通文件

-c: 字符设备

-b: 块设备

逻辑操作符:

-a: 与

-o: 或

!: 非

eg:

[root@k8s-master test5]# sh t1.sh 
test 1 -eq 2: false
n1+n2:
[n1+n2]: 3
[root@k8s-master test5]# cat t1.sh 
#!/bin/bash
n1=1
n2=2
if test $[n1] -eq $[n2]
then
  echo "test $[n1] -eq $[n2]: true"
else
  echo "test $[n1] -eq $[n2]: false"
fi

echo "n1+n2:"
r=$[n1+n2]
echo "[n1+n2]: $r"
[root@k8s-master test5]# 
[root@k8s-master test5]# sh t2.sh 
$s1 = $s2: false
[root@k8s-master test5]# cat t2.sh 
#!/bin/bash

s1='hello'
s2='world'
if test $s1 = $s2
then
  echo '$s1 = $s2: true'
else
 echo '$s1 = $s2: false'
fi
[root@k8s-master test5]# 
[root@k8s-master test5]# sh t3.sh 
test -e ./t0.sh -a -e ./t1.sh: true
[root@k8s-master test5]# cat t3.sh 
#!/bin/bash

if test -e ./t0.sh -a -e ./t1.sh
then
 echo 'test -e ./t0.sh -a -e ./t1.sh: true'
else
 echo 'test -e ./t0.sh -a -e ./t1.sh: false'
fi
[root@k8s-master test5]# 

 


版权声明:本文为Neil_001原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。