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)

三、组合判断

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

相关推荐
Li-Yongjun34 分钟前
深度解析 Linux 内核参数 net.ipv4.tcp_rmem:优化网络性能的关键
linux·网络·tcp/ip
藥瓿亭36 分钟前
K8S认证|CKS题库+答案| 10. Trivy 扫描镜像安全漏洞
linux·运维·服务器·云原生·容器·kubernetes·cks
leo__5201 小时前
在Ubuntu中设置开机自动运行(sudo)指令的指南
服务器·ubuntu·postgresql
Leo.yuan1 小时前
数据湖是什么?数据湖和数据仓库的区别是什么?
大数据·运维·数据仓库·人工智能·信息可视化
程序员JerrySUN2 小时前
Linux 内核内存管理子系统全面解析与体系构建
java·linux·运维
CIb0la2 小时前
Ai自动补全编程工具:llama vscode
运维·开发语言·学习·测试工具·程序人生
rui锐rui2 小时前
大模型模型部署和暴露接口
linux·运维·服务器
Clownseven2 小时前
云防火墙(安全组)配置指南:从入门到精通端口开放 (2025)
服务器·安全
BJ_Bonree2 小时前
博睿数据×华为, 共筑智慧金融新未来
运维
孙克旭_2 小时前
day030-Shell自动化编程-函数
linux·运维·自动化