shell -条件测试

目录

前言

一、条件测试常用语法

1、语法总结

2、语法示例

 二、文件测试表达式

1.选项总述

2、示例 

三、字符串测试表达式

1、用法概述

2、用法示例 

四、整数二元比较

1、用法概述

2、用法示例

五、逻辑操作符

六、不同表达式区别·

 


 


前言

这篇文章介绍了shell中的条件测试常用语法和区别,文件测试表达式、字符串测试表达式、整数比较、逻辑操作符 


 

一、条件测试常用语法

1、语法总结

2、语法示例

  • test条件测试
test  -f file && echo true || echo false

如果文件存在,输出true,否则输出fales

[root@localhost scripts]# test -f file1 && echo true || echo false 

false

[root@localhost scripts]# touch file1

[root@localhost scripts]# test -f file1 && echo true || echo false 

true

  • []条件测试
[root@localhost scripts]# [ -f /scripts/file1 ] && echo 1 || echo 0

1

[root@localhost scripts]# rm file1 

rm:是否删除普通空文件 "file1"?y

[root@localhost scripts]# [ -f /scripts/file1 ] && echo 1 || echo 0

0
  • [[]] 语法测试
[root@localhost scripts]# [[ -f /scripts/file2 ]] && echo y || echo n

n

[root@localhost scripts]# touch file2

[root@localhost scripts]# [[ -f /scripts/file2 ]] && echo y || echo n

y

 

 二、文件测试表达式

1.选项总述

2、示例 

  • 普通文件测试
[root@localhost scripts]# [ -f file3 ] && echo y || echo n
n
[root@localhost scripts]# touch file3
[root@localhost scripts]# ls -l
总用量 0
-rw-r--r--. 1 root root 0 11月  8 14:36 file2
-rw-r--r--. 1 root root 0 11月  8 14:48 file3
[root@localhost scripts]# [ -f file3 ] && echo y || echo n
y
  • 目录文件测试
[root@localhost scripts]# mkdir test
[root@localhost scripts]# [ -f test ] && echo y || echo n
n
[root@localhost scripts]# [ -e test ] && echo y || echo n
y
[root@localhost scripts]# [ -d test ] && echo y || echo n
y
[root@localhost scripts]# [ -d file3 ] && echo y || echo n
n
  • 测试文件属性
-rw-r--r--. 1 root root 0 11月  8 14:36 file2
-rw-r--r--. 1 root root 0 11月  8 14:48 file3
drwxr-xr-x. 2 root root 6 11月  8 14:50 test
[root@localhost scripts]# [ -x file3 ] && echo y || echo n
n
[root@localhost scripts]# [ -r file3 ] && echo y || echo n
y
[root@localhost scripts]# [ -w file3 ] && echo y || echo n
y
[root@localhost scripts]# [ -w file3 ] && echo y || echo n

 

三、字符串测试表达式

1、用法概述

2、用法示例 

[root@localhost scripts]# var="lodboy"
[root@localhost scripts]# [ -n "$var" ] && echo 1 || echo 0
1
[root@localhost scripts]# [ -z "$var" ] && echo 1 || echo 0
0
[root@localhost scripts]# [ "abc" = "abc" ] && echo 1 || echo 0
1
[root@localhost scripts]# [ "$var" = "oldboy" ] && echo 1 || echo 0
0
[root@localhost scripts]# [ "$var" = "lodboy" ] && echo 1 || echo 0
1

 

四、整数二元比较

1、用法概述

2、用法示例

  • 注意:

 

[root@localhost script]# [ 1 = 2 ] && echo 1 || echo 0
0
[root@localhost script]# [ 1 -eq 2 ] && echo 1 || echo 0
0

五、逻辑操作符

 

 

六、不同表达式区别·

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值