Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if folder is empty or have folder file use shell-script? [duplicate]

Tags:

linux

shell

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?

like image 695
fifty arashi Avatar asked Nov 23 '10 07:11

fifty arashi


People also ask

How do you check if a folder is empty or not in shell script?

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.

How do you check if a folder is empty or not?

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.

How check if directory is empty Linux?

Empty dirs in current dir: find . -type d -empty . In addition, empty files: find . -type f -empty in current dir and deeper.

How do you check if a folder contains a file in Linux?

[[ -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!"


1 Answers

From the Bash FAQ #4 -- How can I check whether a directory is empty or not?

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.

Note

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

like image 110
SiegeX Avatar answered Oct 05 '22 02:10

SiegeX