Bash Shell Check Whether a Directory is Empty or Not

Bash Shell Check Whether a Directory is Empty or Not

To check whether a directory is empty or not in a Bash shell, you can use the ls command with the -A and -1 options to list the files in the directory, and then use the wc command to count the number of lines in the output. If the directory is empty, the output will contain zero lines.

Here is an example of how to check whether the directory /tmp is empty or not:

if [[ $(ls -A1 /tmp | wc -l) -eq 0 ]]; then
  echo "Directory is empty"
else
  echo "Directory is not empty"
fi
Source:ww‮ual.w‬tturi.com

This will check the number of files in the /tmp directory and print "Directory is empty" if the directory is empty, or "Directory is not empty" if the directory contains any files.

The -A option tells ls to list all files, including hidden files (files that start with a dot). The -1 option tells ls to print one file per line.

The wc command counts the number of lines in the output of ls. The -l option tells wc to count the number of lines.

The [[ ... ]] syntax is used to test the result of the command and execute the appropriate code based on the result. The -eq operator is used to test for equality. If the output of ls | wc -l is equal to 0, the test evaluates to true and the code within the then block is executed. If the output is not equal to 0, the test evaluates to false and the code within the else block is executed.

You can use this technique to check whether any directory is empty or not. Simply replace /tmp with the path to the directory you want to check.

Keep in mind that this method will not count directories as files. If the directory contains only subdirectories and no regular files, the script will consider the directory to be empty. To also count directories as files, you can use the find command instead of ls. For example:

if [[ $(find /tmp -mindepth 1 -maxdepth 1 | wc -l) -eq 0 ]]; then
  echo "Directory is empty"
else
  echo "Directory is not empty"
fi

This will use the find command to list all files and directories in the /tmp directory and count the number of items with wc. The -mindepth 1 and -maxdepth 1 options tell find to only list files and directories in the current directory, not in any subdirectories.

Created Time:2017-10-27 14:56:35  Author:lautturi