Shell : Deleting empty subdirectories in a directory

Shell Scripting @ Freshers.in

In Unix-based operating systems, it is common to write shell scripts to automate tasks. One common task is deleting empty subdirectories in a directory. This is useful to clean up directories and improve organization.

To delete empty subdirectories in a shell script, we can use the find command with the -type d option to find directories, and the -empty option to find empty directories. We can also use the -exec option to execute a command on each matching file or directory.

Here’s an example script that takes a directory name as an argument and deletes all the empty subdirectories in it:

#!/bin/bash
dir=$1
if [ -d "$dir" ]; then
  echo "Deleting empty subdirectories in $dir..."
  find "$dir" -type d -empty -exec rmdir {} \;
  echo "Done."
else
  echo "$dir is not a directory."
fi

The first line #!/bin/bash is called a shebang and specifies which shell should be used to execute the script. In this case, we are using the bash shell.

The script takes a directory name as an argument and stores it in the dir variable.

The if statement checks if the directory exists using the -d option. If it does, the script outputs a message saying that it is deleting empty subdirectories in the directory using the echo command.

The find command is used to find empty subdirectories in the specified directory. The -type d option finds directories, and the -empty option finds empty directories. The -exec option is used to execute the rmdir command on each empty directory found.

The rmdir command is used to remove directories. The {} symbol is a placeholder for the directory name found by find.

After deleting all empty subdirectories, the script outputs a message saying that it is done using the echo command.

If the directory does not exist, the script outputs a message saying that it is not a directory using the echo command.

We can run the script by saving it as a file, for example delete-empty-subdirs.sh, and then making it executable using the chmod command:

chmod +x delete-empty-subdirs.sh

We can then execute the script by passing a directory name as an argument, for example:

./delete-empty-subdirs.sh example_directory

This will delete all empty subdirectories in the example_directory. Deleting empty subdirectories in a directory is a common task in shell scripting. We can use the find command with the -type d and -empty options to find empty subdirectories, and the -exec option to execute the rmdir command on each empty directory found.

Other urls to refer

  1. PySpark Blogs
Author: user

Leave a Reply