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

    你可能感兴趣的文章
    Pandas数据结构之DataFrame常见操作
    查看>>
    pandas整合多份csv文件
    查看>>
    pandas某一列转数组list
    查看>>
    Pandas模块,我觉得掌握这些就够用了!
    查看>>
    Pandas玩转文本处理!
    查看>>
    pandas的to_sql方法中使用if_exists=‘replace‘
    查看>>
    pandas读取parquet报错
    查看>>
    spring5-介绍Spring框架
    查看>>
    PandoraFMS 监控软件 任意文件上传漏洞复现
    查看>>
    Parallel.ForEach的基础使用
    查看>>
    parallels desktop for mac安装虚拟机 之parallelsdesktop密钥 以及 parallels desktop安装win10的办公推荐可以提高办公效率...
    查看>>
    ParseChat应用源码ios版
    查看>>
    PAT 1027 Colors in Mars
    查看>>
    PAT 1127 ZigZagging on a Tree[难]
    查看>>
    PAT 2-07. 素因子分解(20)
    查看>>
    PAT-乙级-1040 有几个PAT
    查看>>
    PATA1038题解(需复习)
    查看>>
    Patching Array
    查看>>
    Path does not chain with any of the trust anchors
    查看>>
    Path形状获取字符串型变量数据
    查看>>