Checking if a directory is empty using bash script

Checking whether a directory is empty can be acheived using an if-else construct.

It has the following syntax:

if [[ condition ]] # there must be a space between the condition and the square brackets
then
  <execute command>
else # this is optional
  <execute another command>
fi # this closes the statement


Condition for checking if empty:

-z "$(ls -A /path/to/dir/)"


So in summary this can be achieved as follows:

temp_dir = "some-path"

if [ -z "$(ls -A $temp_dir)" ]; then
   echo "$temp_dir empty"
else
    echo "Not Empty"
fi


Sources:




Enjoy Reading This Article?

Here are some more articles you might like to read next:

  • Google Gemini updates: Flash 1.5, Gemma 2 and Project Astra
  • Displaying External Posts on Your al-folio Blog
  • Can Machine Learning Help Predict Heart Disease? A Data Science Exploration
  • Predicting House Prices; MLR vs RFR
  • Predicting House Prices; SVC vs Random Forest