bash sh:测试文件是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8921441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:21:42  来源:igfitidea点击:

sh: Test for existence of files

bashsh

提问by ikegami

How does one test for the existence of files in a directory using bash?

如何使用 测试目录中文件的存在bash

if ... ; then
   echo 'Found some!'
fi

To be clear, I don't want to test for the existence of a specificfile. I would like to test if a specific directory contains anyfiles.

明确地说,我不想测试特定文件的存在。我想测试特定目录是否包含任何文件。



I went with:

我和:

(
   shopt -s dotglob nullglob
   existing_files=( ./* )
   if [[ ${#existing_files[@]} -gt 0 ]] ; then
      some_command "${existing_files[@]}"
   fi
)

Using the array avoids race conditions from reading the file list twice.

使用数组可以避免竞争条件读取文件列表两次。

回答by Conrad Shultz

From the man page:

从手册页:

   -f file
          True if file exists and is a regular file.

So:

所以:

if [ -f someFileName ]; then echo 'Found some!'; fi

Edit: I see you already got the answer, but for completeness, you can use the info in Checking from shell script if a directory contains files- and lose the dotglob option if you want hidden files ignored.

编辑:我看到你已经得到了答案,但为了完整起见,如果目录包含文件,你可以使用从 shell 脚本检查中的信息- 如果你想忽略隐藏文件,则丢失 dotglob 选项。

回答by Conrad Shultz

I typically just use a cheap ls -A to see if there's a response.

我通常只使用便宜的 ls -A 来查看是否有响应。

Pseudo-maybe-correct-syntax-example-ahoy:

伪可能是正确的语法示例啊:

if [[ $(ls -A my_directory_path_variable ) ]] then....

edit, this will work:

编辑,这将工作:

myDir=(./*) if [ ${#myDir[@]} -gt 1 ]; then echo "there's something down here"; fi

myDir=(./*) if [ ${#myDir[@]} -gt 1 ]; then echo "there's something down here"; fi

回答by paxdiablo

You can use lsin an ifstatement thus:

您可以lsif语句中使用:

if [[ "$(ls -a1 | egrep -v '^\.$|^\.\.$')" = "" ]] ; then echo empty ; fi

or, thanks to ikegami,

或者,感谢池上,

if [[ "$(ls -A)" = "" ]] ; then echo empty ; fi

or, even shorter:

或者,甚至更短:

if [[ -z "$(ls -A)" ]] ; then echo empty ; fi

These basically list all files in the current directory (including hidden ones) that are neither .nor ...

这些基本上列出了当前目录中的所有文件(包括隐藏的),既不是也不....

If that list is empty, then the directory is empty.

如果该列表为空,则该目录为空。

If you want to discount hidden files, you can simplify it to:

如果要打折隐藏文件,可以简化为:

if [[ "$(ls)" = "" ]] ; then echo empty ; fi


A bash-only solution (no invoking external programs like lsor egrep) can be done as follows:

一个bash-only 解决方案(不调用外部程序,如lsegrep)可以按如下方式完成:

emp=Y; for i in *; do if [[ $i != "*" ]]; then emp=N; break; fi; done; echo $emp

It's not the prettiestcode in the world, it simply sets empto Yand then, for every real file, sets it to Nand breaks from the forloop for efficiency. If there were zero files, it stays as Y.

它不是世界上最漂亮的代码,它只是设置empY,然后对于每个真实文件,将其设置为N并中断for循环以提高效率。如果有零个文件,它保持为Y.

回答by Steve Robillard

Try this

尝试这个

if [ -f /tmp/foo.txt ]
then
    echo the file exists
fi

ref: http://tldp.org/LDP/abs/html/fto.html

参考:http: //tldp.org/LDP/abs/html/fto.html

you may also want to check this out: http://tldp.org/LDP/abs/html/fto.html

你可能还想看看这个:http: //tldp.org/LDP/abs/html/fto.html

How about this for whether directory is empty or not

这个目录是否为空怎么样

$ find "/tmp" -type f -exec echo Found file {} \;

回答by Xaxxon

#!/bin/bash

if [ -e  ]; then
        echo "File exists"
else 
       echo "Files does not exist"
fi 

回答by Keith Thompson

I don't have a good pure sh/bash solution, but it's easy to do in Perl:

我没有好的纯 sh/bash 解决方案,但在 Perl 中很容易做到:

#!/usr/bin/perl

use strict;
use warnings;

die "Usage: 
if emptydir dir ; then
    echo "dir is empty"
else
    echo "dir is not empty"
fi
dir\n" if scalar @ARGV != 1 or not -d $ARGV[0]; opendir my $DIR, $ARGV[0] or die "$ARGV[0]: $!\n"; my @files = readdir $DIR; closedir $DIR; if (scalar @files == 2) { # . and .. exit 0; } else { exit 1; }

Call it something like emptydirand put it somewhere in your $PATH, then:

emptydir将其命名为类似并将其放在您的某个位置$PATH,然后:

# tested on Linux BASH

directory=

if test $(stat -c %h $directory) -gt 2;
then
   echo "not empty"
else
   echo "empty"
fi

It dies with an error message if you give it no arguments, two or more arguments, or an argument that isn't a directory; it's easy enough to change if you prefer different behavior.

如果你不给它任何参数、两个或更多参数,或者一个不是目录的参数,它就会死,并显示一条错误消息;如果您喜欢不同的行为,那么改变就很容易了。

回答by Vidul

if ( shopt -s nullglob ; perl -e'exit !@ARGV' ./* ) ; then
   echo 'Found some!'
fi

回答by ikegami

For fun:

为了娱乐:

##代码##

(Doesn't check for hidden files)

(不检查隐藏文件)