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:

  • 6 months a data engineer…
  • Failing forward; Lessons from Airflow error alerts.
  • Learning while working.
  • Can Machine Learning Help Predict Heart Disease? A Data Science Exploration
  • Predicting House Prices; MLR vs RFR