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?
There are many ways to find out if a directory is empty or not under Linux and Unix bash shell. You can use the find command to list only files. In this example, find command will only print file name from /tmp. If there is no output, directory is empty.
File. list() is used to obtain the list of the files and directories in the specified directory defined by its path name. This list of files is stored in a string array. If the length of this string array is greater than 0, then the specified directory is not empty.
Empty dirs in current dir: find . -type d -empty . In addition, empty files: find . -type f -empty in current dir and deeper.
[[ -d <directory> ]] && echo "This directory exists!" [ -d <directory> ] && echo "This directory exists!" Let's say that you want to check if the “/etc” directory exists for example. Using the shorter syntax, you would write the following command. [ -d /etc ] && echo "This directory exists!"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With