bashshellunix

bash shell script to delete directory only if there are no files


Ok so I am writing a shell script to delete a directory but only if there are no files inside.

what I want to do is have an if statement that will check if there are files in the directory and if there are files ask the user if they want to delete the files first and then delete the directory.

I have looked quite a bit into this and have found a way to check if files exist in the directory but I haven't been able to make it past that stage.

here is the if statement I have created so far to check if files exist in a directory:

echo "Please type the name of the directory you wish to remove "

                read dName
        shopt -s nullglob
        shopt -s dotglob
        directory=$Dname

        if [ ${#directory[@]} -gt 0 ];
        then
                echo "There are files in this directory! ";
        else
                echo "This directory is ok to delete! "
        fi
        ;;

Solution

  • You don't need to check; rmdir will only delete empty directories.

    $ mkdir foo
    $ touch foo/bar
    $ rmdir foo
    rmdir: foo: Directory not empty
    $ rm foo/bar
    $ rmdir foo
    $ ls foo
    ls: foo: No such file or directory
    

    In a more practical setting, you can use the rmdir command with an if statement to ask the user if they want to remove everything.

    if ! rmdir foo 2> /dev/null; then
        echo "foo contains the following files:"
        ls foo/
        read -p "Delete them all? [y/n]" answer
        if [[ $answer = [yY] ]]; then
            rm -rf foo
        fi
    fi