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

    你可能感兴趣的文章
    Notepad++在线和离线安装JSON格式化插件
    查看>>
    notepad++最详情汇总
    查看>>
    notepad++正则表达式替换字符串详解
    查看>>
    notepad如何自动对齐_notepad++怎么自动排版
    查看>>
    Notes on Paul Irish's "Things I learned from the jQuery source" casts
    查看>>
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    NotImplementedError: Could not run torchvision::nms
    查看>>
    nova基于ubs机制扩展scheduler-filter
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘html-webpack-plugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe` failed with exit code: 1
    查看>>