i have a question
i try some function like
DIR=/path/tmp/
if [ -d "$DIR" ]; then
and
if [ -f "$DIR" ]; then
but only check /path/tmp this path
how can i do?
i have a question
i try some function like
DIR=/path/tmp/
if [ -d "$DIR" ]; then
and
if [ -f "$DIR" ]; then
but only check /path/tmp this path
how can i do?
shopt -s nullglob dotglob
files=(*)
(( ${#files[*]} )) || echo directory is empty
shopt -u nullglob dotglob
This small script fills the array files
with each file found in the path expansion *
. It then checks to see the size of the array and if it's 0 it prints 'directory is empty'. This will work with hidden files thanks to the use of dotglob
.
Answers which ask to parse ls
is in general a bad idea and poor form. To understand why, read Why you shouldn't parse the output of ls
You can use ls -A
for this:
if [ "$(ls -A "$DIR" 2> /dev/null)" == "" ]; then
# The directory is empty
fi
-A
shows all hidden files and directories except the .
and ..
that are always there, so it will be blank in an empty directory and non-blank in a directory with any files or subdirectories.
The 2> /dev/null
throws away any error messages ls
may print (note that checking a non-existant directory will yield a false positive, but you said you already checked that it existed). Checking a directory where you do not have read access also yields a false positive.
[ -z "$(find "$DIR" -maxdepth 0 -empty)" ] || echo "$DIR is empty!"
find
has predicate -empty
which tests if a directory or file is empty, so it will list the directory only if it's empty. -z
tests if output of find is empty. If it is, then the directory contains entries, if it isn't then it's empty.
In other code words:
[ -n "$(find "$DIR" -maxdepth 0 -empty)" ] && echo "$DIR is empty!"
Another quite nice one:
if ! ls -AU "$DIR" | read _; then
echo "$DIR is empty!"
fi
why don't use ls -v
? so will print out empty if no file such as
if $(ls -v $DIR)
This tells me if the directory is empty or if it's not, the number of files it contains.
directory="/path/tmp"
number_of_files=$(ls -A $directory | wc -l)
if [ "$number_of_files" == "0" ]; then
echo "directory $directory is empty"
else
echo "directory $directory contains $number_of_files files"
fi
To do this using only shell built-ins (it should work for all shells I have worked with):
if test "`echo /tmp/testdir/* /tmp/testdir/.?*`" = \
"/tmp/testdir/* /tmp/testdir/.."; then
[...]
fi
We do not check /tmp/testdir/.* because that will expand to /tmp/testdir/. /tmp/testdir/.. for an empty folder.
Another built-in-only variant:
for i in /tmp/testdir/* /tmp/testdir/.?*; do
test -e $i || break
[...]
break
done
rmdir "$DIR"
If $?
is 1, the directory isn't empty. If 0, it was empty and it gets removed.
You may recreate it if you don't intend to remove it: mkdir "$DIR"