Shell——条件判断

目录

一、格式

二、常用条件判断

三、组合判断


一、格式

test+表达式或者使用中括号[](中括号前后一定要有空格,Linux中没有空格一般都会看作一个整体变量

复制代码
[root@hadoop-master sh_test]# a=hi
[root@hadoop-master sh_test]# test $a = hi
[root@hadoop-master sh_test]# echo $?
0

[root@hadoop-master sh_test]# test $a = hello
[root@hadoop-master sh_test]# echo $?
1

# 注意等号需要空格

[root@hadoop-master sh_test]# [ $a = hello ]
[root@hadoop-master sh_test]# echo $?
1

二、常用条件判断

(一)两整数

  1. -eq(equal):等于

  2. -lt(less than):小于

  3. -gt(greater than):大于

  4. -ne(not equal):不等于

  5. -le(less equal):小于等于

  6. -ge(greater equal):大于等于

  7. 若是字符串,使用"="或者"!="判断是否相等

    [root@hadoop-master sh_test]# [ 2 < 8 ]
    -bash: 8: 没有那个文件或目录

    [root@hadoop-master sh_test]# [ 2 -ge 8 ]
    [root@hadoop-master sh_test]# echo $?
    1

(二)文件权限

  1. -r:读(read)
  2. -w:写(write)
  3. -x:执行(execute)
javascript 复制代码
[root@hadoop-master sh_test]# ll
总用量 8
-rwxr-xr-x. 1 root root  35 10月 21 15:13 add.sh
-rwxr-xr-x. 1 root root 112 10月 21 11:26 hello.sh
-rw-r--r--. 1 root root   0 10月 21 16:02 test.sh

[root@hadoop-master sh_test]# [ -x add.sh ]
[root@hadoop-master sh_test]# echo $?
0

[root@hadoop-master sh_test]# [ -x test.sh ]
[root@hadoop-master sh_test]# echo $?
1

(三)文件类型

  1. -e:文件存在(existence)
  2. -f:文件存在并且是一个常规文件(file)
  3. -d:文件存在并且是一个目录(directory)

三、组合判断

使用&&与||将多个条件判断相连起来,其中&&的优先级更高一些

相关推荐
是小胡嘛2 小时前
C++之Any类的模拟实现
linux·开发语言·c++
口袋物联2 小时前
设计模式之工厂模式在 C 语言中的应用(含 Linux 内核实例)
linux·c语言·设计模式·简单工厂模式
qq_479875433 小时前
X-Macros(1)
linux·服务器·windows
笨笨聊运维4 小时前
CentOS官方不维护版本,配置python升级方法,无损版
linux·python·centos
ζั͡山 ั͡有扶苏 ั͡✾4 小时前
EFK 日志系统搭建完整教程
运维·jenkins·kibana·es·filebeat
jun_bai5 小时前
python写的文件备份网盘程序
运维·服务器·网络
Warren985 小时前
Python自动化测试全栈面试
服务器·网络·数据库·mysql·ubuntu·面试·职场和发展
HIT_Weston5 小时前
39、【Ubuntu】【远程开发】拉出内网 Web 服务:构建静态网页(二)
linux·前端·ubuntu
欢喜躲在眉梢里5 小时前
CANN 异构计算架构实操指南:从环境部署到 AI 任务加速全流程
运维·服务器·人工智能·ai·架构·计算
weixin_537765806 小时前
【容器技术】虚拟化原理与Docker详解
运维·docker·容器