very small bash script question
Lawrence Chim writes:
> Does anyone know how to check a directory is empty
> in bash script?
>
> lawrence,
>
This seems to work for me.
----------------------- dir_is_empty -------------------
#! /bin/bash
# syntax dir_is_empty [optional_directory]
# return 0 if it is empty
# 1 if it isn't empty (but is a directory)
# 2 if parameter is not a directory (error)
# or too many args given (error)
# Thee 2 varriables must be set for bash to expand the way
# we want it to. See man bash(1).
glob_dot_filenames=1
allow_null_glob_expansion=1
DIR="."
case $# in
0 ) DIR="." ;;
1 ) DIR=$1
if [ ! -d $DIR ] ; then
echo >&1 $DIR is not a directory
exit 2
fi ;;
* ) echo >&1 "syntax is $0 [optional directory]"
exit 2 ;;
esac
X="`(cd $DIR ; echo *)`"
if [ "$X" = ". .." ] ; then
exit 0
else
exit 1
fi
------------------------------------------------------------------------
Testing it.
ls -al Empty Non1 Non2
Empty:
total 3
drwxr-xr-x 2 rs rs 1024 Mar 8 16:56 .
drwxr-xr-x 11 rs rs 2048 Mar 8 17:26 ..
Non1:
total 4
drwxr-xr-x 2 rs rs 1024 Mar 8 16:56 .
drwxr-xr-x 11 rs rs 2048 Mar 8 17:26 ..
-rw-r--r-- 1 rs rs 29 Mar 8 16:56 date
Non2:
total 4
drwxr-xr-x 2 rs rs 1024 Mar 8 16:56 .
drwxr-xr-x 11 rs rs 2048 Mar 8 17:26 ..
-rw-r--r-- 1 rs rs 29 Mar 8 16:56 .date
./dir_is_empty Empty/ ; echo $?
0
./dir_is_empty Non1/ ; echo $?
1
./dir_is_empty Non2/ ; echo $?
1
./dir_is_empty ; echo $?
1
./dir_is_empty dir_is_emptry ; echo $?
dir_is_emptry is not a directory
2
bash%
Reply to: