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)

三、组合判断

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

相关推荐
buhuizhiyuci2 分钟前
【Linux 篇】数字世界的水流蓄水池 —— IO 缓冲区机制深度实战解析
linux·运维·服务器·c++
贝锐6 分钟前
多校区互通、临时联网、远程运维,校园网络升级用蒲公英更省心!
运维·组网
骇客野人10 分钟前
Linux 服务器 Python 版 MCP 服务部署整体方案(适配 Claude/Cursor/自研Agent)
linux·服务器·python
啦啦啦啦啦zzzz34 分钟前
moduo网络库 Acceptor TcpConnection
服务器·网络·c++·reactor·网络库
游戏开发爱好者834 分钟前
App Store 上传 IPA 自动化,.p8 密钥认证与 CI/CD 接入实战
android·运维·ci/cd·小程序·uni-app·自动化·iphone
天疆说42 分钟前
04 稳定性与性能调优实录:OOM 崩溃、并发槽位、前缀缓存与 DSpark 调参
linux·运维·缓存
微硬创新43 分钟前
大点数模拟量采集落地:耐达讯自动化32路0-20mA适配PROFINET总线实践解析
运维·人工智能·网络协议·自动化·信息与通信
星卯教育tony44 分钟前
NOI Linux 2.0 服务器多用户网页桌面部署方案(腾讯云轻量Ubuntu20.04专属版 CSP复赛比赛环境搭建免安装虚拟机 )
linux·服务器·腾讯云
GIS数据转换器1 小时前
村镇无人机物流配送与跨域监测一体化平台
大数据·运维·人工智能·科技·无人机
Forever Nore2 小时前
LeetCode 14 最长公共前缀 - 纵向扫描
linux·服务器·leetcode