Sh: Check for files

How to check for files in a directory using bash?

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

To be clear, I do not want to check for a specific file. I would like to check if any particular directory contains any files.


I went with:

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

Using an array avoids race conditions from reading a list of files twice.

+5
source share
8 answers

I usually use cheap ls -A to see if there is an answer.

Pseudo-possibly-correct-syntax Example-Ahoy:

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

this will work:

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

+7
source

On the man page:

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

So:

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

: , , script, - dotglob, , .

+9

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

,

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

ls if, :

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

, ,

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

, :

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

( ), ., ...

, .

, :

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

A bash - ( ls egrep) :

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

, emp Y, N for . , Y.

+3
#!/bin/bash

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

sh/ bash, Perl:

#!/usr/bin/perl

use strict;
use warnings;

die "Usage: $0 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;
}

- emptydir - $PATH, :

if emptydir dir ; then
    echo "dir is empty"
else
    echo "dir is not empty"
fi

He dies with an error message if you do not give him arguments, two or more arguments, or an argument that is not a directory; it is easy to change if you prefer a different behavior.

+1
source
# tested on Linux BASH

directory=$1

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

For pleasure:

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

(Does not check for hidden files)

0
source

All Articles