博客
关于我
Shell条件判断语句上
阅读量:167 次
发布时间:2019-02-28

本文共 1153 字,大约阅读时间需要 3 分钟。

按照文件类型进行判断

在实际工作中,我们经常需要根据文件的存在性和类型来判断系统状态或执行某些操作。以下是常用的判断方法:

两种判断格式

在Shell命令中,文件存在性和文件类型判断通常使用以下格式:

  • test -e /path/to/file

    如果文件存在,命令执行成功,输出0;否则输出非零数值。可以结合命令执行结果进行判断,例如:

    if test -e /root/install.log; then echo "yes"; else echo "no"; fi

    如果命令成功,输出"yes";否则输出"no"。

  • [ -e /path/to/file ]

    该格式也可以用于判断文件是否存在,但需要注意文件类型。对于目录,通常使用[ -d /path/to/dir ]

  • 实战

    以下是实际案例示例:

  • 列示例文件:

    [root@localhost ~]# lsabc   cansy  Downloads  Pictures  Templatesabcd ChangeLog-2.6.0  initial-setup-ks.cfg  Public  test.txtanaconda-ks.cfg  Desktop  linux-2.6.39.tar.bz2  sh  Videoscangls  Documents  Music  student.txt  XshellXftpPortable.zip
  • 判断特定文件是否存在:

    [root@localhost ~]# [ -e /root/test.txt ][root@localhost ~]# [ -e /root/test.txt2 ]

    输出结果分别为:

    yesno

    然后执行:

    echo $?

    输出结果为:

    1
  • 判断目录是否存在并输出结果:

    [root@localhost ~]# [ -d /root ] && echo "yes" || "no"

    输出结果为:

    yes
  • 按照文件权限判断

    文件权限判断是系统管理中的常见操作,通常用于脚本自动化处理。以下是判断文件权限的命令示例:

  • 判断文件是否可写:

    [root@localhost ~]# [ -w /root/test.txt ] && echo "yes" || "no"

    输出结果为:

    yes

    说明:文件存在且可写。

  • 判断文件是否可读:

    [root@localhost ~]# [ -r /root/test.txt ] && echo "yes" || "no"

    输出结果为:

    yes
  • 判断文件是否可执行:

    [root@localhost ~]# [ -x /root/test.sh ] && echo "yes" || "no"

    输出结果为:

    yes

    说明:文件存在并可执行。

  • 转载地址:http://oxhj.baihongyu.com/

    你可能感兴趣的文章
    ping 命令的七种用法,看完瞬间成大神
    查看>>
    Pinia入门(快速上手)
    查看>>
    Pinia:$patch的使用场景
    查看>>
    Pinia:$subscribe()的使用场景
    查看>>
    Pinpoint对Kubernetes关键业务模块进行全链路监控
    查看>>
    Pinterest 大规模缓存集群的架构剖析
    查看>>
    pintos project (2) Project 1 Thread -Mission 1 Code
    查看>>
    PinYin4j库的使用
    查看>>
    PIP
    查看>>
    pip install goose-extractor // SyntaxError: Missing parentheses in call to 'print'
    查看>>
    pip install mysqlclient报错
    查看>>
    pip install 出现报asciii码错误的解决
    查看>>
    pip throws TypeError: parse() got an unexpected keyword argument ‘transport_encoding‘ 在尝试安装新软件包时
    查看>>
    pip 下载慢
    查看>>
    pip 升级报错AttributeError: ‘NoneType’ object has no attribute ‘bytes’
    查看>>
    pip 安装opencv-python卡死
    查看>>
    pip 安装出现异常
    查看>>
    Pip 安装失败:需要 SSL
    查看>>
    Pip 安装挂起
    查看>>
    pip 或 pip3 为 Python 3 安装包?
    查看>>