How do I check if a directory is empty or not in ksh on AIX?If files exist I need to remove files only.
Check in ksh if a directory is empty
directory;ksh
Here's a POSIX-compliant way of testing whether dir is empty using only built-in shell constructs. The set command sets the positional arguments to dot files (including the always-existing . and ..) followed by non-dot files. If the directory is empty then the .* glob only matches . and .., and the * glob matches nothing so remains unexpanded.set dir/.* dir/*[ $1 = dir/. ] && [ $2 = dir/.. ] && ! [ -e $3 ] && ! [ -L $3 ]This works on ATT ksh but fails with some shells that omit the . and .. entries. To be more portable, you need to also allow for .* to match nothing.set dir/.* dir/*case $# in  0) true;; # can't happen in a standard shell, this is for shells with nullglob  2) { [ $1 = dir/.* ] && [ $2 = dir/* ] && ! [ -e $1 ] && ! [ -L $1 ] && ! [ -e $2 ] && ! [ -L $2 ]; } ||     { [ $1 = dir/. ] && [ $2 = dir/.. ]; };;  3) [ $1 = dir/. ] && [ $2 = dir/.. ] && ! [ -e $3 ] && ! [ -L $3 ];;  *) false;;esacRecent enough versions of ksh allow a simpler test, but I think AIX's is too old (even its ksh93). Here's how you can test whether dir is empty in a recent enough ksh93:FIGNORE='.?(.)'; set -- ~(N)dir/*; [[ $# -eq 0 ]]or alternativelyFIGNORE=; set -- dir/*; [[ $# -eq 2 ]]An alternative approach is to call find. This is simpler in that find doesn't treat dot files specially and doesn't have anything like the shell's difficulty to distinguish between a pattern that matches a single file and a pattern that is left unexpanded because it matches nothing.[ -z $(find dir/. -name . -o -print | head -n 1) ]