广告
返回顶部
首页 > 资讯 > 服务器 >使用Bash Shell检查文件是否存在的方法
  • 410
分享到

使用Bash Shell检查文件是否存在的方法

是否存在文件方法 2022-06-04 21:06:10 410人浏览 安东尼
摘要

前言 大家在工作的时候可能经常会遇到这样的需求,在类Unix系统的Bash环境下,怎样检查文件是否存在呢?既然有需求,当然就有解决的办法了,shell中的test命令,可以用来检测文件的类型或者比较数值是否

前言

大家在工作的时候可能经常会遇到这样的需求,在类Unix系统的Bash环境下,怎样检查文件是否存在呢?既然有需求,当然就有解决的办法了,shell中的test命令,可以用来检测文件的类型或者比较数值是否相等,该命令也能用来检查文件是否存在。

可以用如下的命令来进行检查:


test -e filename
[ -e filename ]
 
test -f filename
[ -f filename ]

下面的命令,则使用Shell的条件表达式,判断/etc/hosts文件是否存在:


[ -f /etc/hosts ] && echo "Found" || echo "Not found"

该组合命令会输出以下内容:


Found

更常见的用法,则是将test命令放置在if..else..fi条件判断的条件表达式,然后在其中写上不同的分支逻辑


#!/bin/bash
file="/etc/hosts"
if [ -f "$file" ]
then
 echo "$file found."
else
 echo "$file not found."
fi

检测文件属性的相关操作符

如果文件存在,并且具有相应的属性,如下的操作符都会返回true:


  -b FILE
    FILE exists and is block special
  -c FILE
    FILE exists and is character special
  -d FILE
    FILE exists and is a directory
  -e FILE
    FILE exists
  -f FILE
    FILE exists and is a regular file
  -g FILE
    FILE exists and is set-group-ID
  -G FILE
    FILE exists and is owned by the effective group ID
  -h FILE
    FILE exists and is a symbolic link (same as -L)
  -k FILE
    FILE exists and has its sticky bit set
  -L FILE
    FILE exists and is a symbolic link (same as -h)
  -O FILE
    FILE exists and is owned by the effective user ID
  -p FILE
    FILE exists and is a named pipe
  -r FILE
    FILE exists and read permission is granted
  -s FILE
    FILE exists and has a size greater than zero
  -S FILE
    FILE exists and is a Socket
  -t FD file descriptor FD is opened on a terminal
  -u FILE
    FILE exists and its set-user-ID bit is set
  -w FILE
    FILE exists and write permission is granted
  -x FILE
    FILE exists and execute (or search) permission is granted

以上命令,从man test复制而来。

使用上述符号的方法一模一样:


if [ operator FileName ]
then
  echo "FileName - Found, take some action here"
else
 echo "FileName - Not found, take some action here"
fi

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可留言交流。

--结束END--

本文标题: 使用Bash Shell检查文件是否存在的方法

本文链接: https://www.lsjlt.com/news/18958.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作