欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  网络运营

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

程序员文章站 2022-07-04 18:38:43
前言 大家在工作的时候可能经常会遇到这样的需求,在类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

总结

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