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)

三、组合判断

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

相关推荐
ltl8 小时前
校验和与数据完整性:CRC32C、xxHash 与端到端校验
linux
我是小灰灰吖8 小时前
Ubuntu 22.04 设置 CPU 性能模式:提升系统响应速度
linux·ubuntu
ltl8 小时前
持续性能分析:Parca、Pyroscope、Grafana Beyla
linux
ltl8 小时前
Direct I/O 与 O_DIRECT:绕过缓存的得与失
linux
盐焗鹌鹑蛋9 小时前
【Linux】进程控制
linux
微三云 - 廖会灵 (私域系统开发)10 小时前
抖店 OPC 自动化运营系统架构与商业代理分控体系完整解析
运维·系统架构·自动化
G311354227310 小时前
大模型不可用时,业务还能不能继续:企业需要设计降级方案
大数据·服务器·数据库·人工智能·深度学习
办公室马主任11 小时前
华南机械加工企业选MES服务商怎么选?
大数据·运维·人工智能·制造
盐焗鹌鹑蛋11 小时前
【Linux】进程程序替换
linux
鸠摩智首席音效师11 小时前
Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead
linux