博客
关于我
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/

    你可能感兴趣的文章
    SpringBoot中集成screw(螺丝钉)实现数据库表结构文档生成
    查看>>
    PROFINET 模拟器使用教程
    查看>>
    Program type already present: android.support.v4.widget.EdgeEffectCompat
    查看>>
    PyTorch中文版官方教程来啦(附下载)
    查看>>
    Progress Kemp LoadMaster 远程命令执行漏洞复现(CVE-2024-1212)
    查看>>
    Project configuration is not up-to-date with pom.xml. Run Maven->Update Project
    查看>>
    Project Euler 15 Lattice paths
    查看>>
    Project Euler 48 Self powers( 大数求余 )
    查看>>
    Project Euler Problem 12: Highly divisible triangular number
    查看>>
    ProjectEuler 2
    查看>>
    projection介绍及EPSG:4326和EPSG:3857的投射转换
    查看>>
    project打开文件时,显示无法识别此文件格式?
    查看>>
    Prometheus + Grafana on Kubernetes部署
    查看>>
    prometheus + grafana进行服务器资源监控
    查看>>
    Prometheus Alertmanager 告警配置详解
    查看>>
    Prometheus Grafana 展示平台
    查看>>
    Prometheus pushgateway使用详解
    查看>>
    Prometheus 云原生 - Prometheus 数据模型、Metrics 指标类型、Exporter 相关
    查看>>
    Prometheus 云原生 - 基于 file_sd、http_sd 实现 Service Discovery
    查看>>
    Prometheus 云原生 - 微服务监控报警系统 (Promethus、Grafana、Node_Exporter)部署、简单使用
    查看>>