SHELL—条件判断与练习

本文详细介绍了Shell脚本中进行条件判断的方法,包括数值和字符串比较,以及如何检查文件的各种属性,如是否存在、是否为空、文件类型等。通过实际示例,展示了如何判断一个输入数字是否在特定范围内,以及如何识别不同类型的文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.条件判断

test "$a" == "$b" 等同于 [ "$a" == "$b" ]

[ "$a" = "$b" ]		##等于
[ "$a" != "$b" ]	##不等于
[ "$a" -eq "$b" ]	##等于
[ "$a" -ne "$b" ]	##不等于
[ "$a" -le "$b" ]	##小于等于
[ "$a" -ge "$b" ]	##大于等于
[ "$a" -gt "$b" ]	##大于
[ "$a" -lt "$b" ]	##小于
[ "$a" -ne "$b" -a "$a" -gt "$b" ]	##-a必须条件都满足
[ "$a" -ne "$b" -o"$a" -gt "$b" ]	##-a条件至少满足一个
[ -z "$a" ]		##是否为空
[ -e "file" ]		##是否存在
[ -f "file" ]		##普通文件
[ -b "file" ]		##块设备
[ -S "file" ]		##套接字
[ -c "file" ]		##字符设备
[ -L "file" ]		##软链接

二.练习

  • 判断输入的数字是否在10以内

       1.输入是否为空
       2.是否在10以内
       3.1<$a<10 --> yes
       4.$a<1 $a>10 --> no

#!/bin/bash

[ -z "$1" ] && {
    echo "please input a number!"
    exit 1
}

[ "$1" -gt "0" -a "$1" -lt "10" ] && {
    echo "YES"
}||{
    echo "NO"
}
  • 判断文件类型
  • [root@localhost mnt]# vim file.sh 
    [root@localhost mnt]# cat file.sh 
    #!/bin/bash
    [ -z "$1" ] && {
        echo "please enter the file name"
        exit 1
    }
    [ -e "$1" ] || {
        echo "this file does not exist"
        exit 1
    }
    
    [ -f "$1" ] && {
        echo "the file is a normal file"
    }
    
    [ -b "$1" ] && {
        echo "the file is a block device"
    }
    [ -S "$1" ] && {
        echo "the file is a normal socket"
    }
    [ -c "$1" ] && {
        echo "the file is a character device"
    }
    [ -L "$1" ] && {
        echo "the file is a soft link"
    }
    [root@localhost mnt]# sh file.sh test.sh 
    the file is a normal file
    

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值