How to remove non empty Directory in Linux

in Categories , last updated January 20, 2018

I am trying to delete a directory in Linux using the rmdir command. However, I am getting an error message that read as follows:
rmdir: failed to remove 'trip-pictures': Directory not empty
How can I remove non empty directory in Linux using the cli?

There are two commands that one can use to delete directories in Linux operating system:

  1. rmdir command – Delete directory only if it empty
  2. rm command – Delete directory and all files even if it is NOT empty

Procedure to remove non empty directory in Linux

The syntax is:
rm -rf dir-name
rm -rf /path/to/dir/name

Be careful when you use the rm command with -r and -f options. The -r option remove directories and their contents recursively including all files. The -f option to rm command ignore nonexistent files and arguments, never prompt for anything. There is no undo option. So you have to be very careful with rm -rf command. Let us see some examples.


Trying to remove trip-pictures directory with the rmdir command:
rmdir trip-pictures
Sample outputs:

rmdir: failed to remove 'trip-picture/': Directory not empty

To see files inside the directory use ls command
ls -l trip-pictures
ls trip-pictures

To delete all files inside trip-pictures including folder itself run the following rm command:
rm -rf trip-pictures
Remove non empty directory Linux command

How to get visual confirmation about deleting directory

Pass the -v to the rm command:
rm -vrf dir1
rm -vrf dir1 dir2

Sample outputs:

removed 'dir1/resume.txt'
removed 'dir1/bar.txt'
removed 'dir1/foo.txt'
removed directory 'dir1'
removed directory 'dir2/pictures'
removed directory 'dir2'

How to get confirmation prompt before every removal of a dir

You need to pass the -i option to the rm command:
rm -ir foo
Sample outputs:

rm: descend into directory 'foo/'? y
rm: remove regular empty file 'foo/bash.tar.gz'? y
rm: remove regular empty file 'foo/db.sql'? y
rm: remove directory 'foo/'? y

To get prompt once before removing more than three files, or when removing recursively; less intrusive than -i, while still giving protection against most mistakes pass the -I option:
rm -Ir bar
Sample outputs:

rm: remove 1 argument recursively? y

For more info see the rm and rmdir command man pages by typing the following command:
man rm
man rmdir

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Share this on (or read 0 comments/add one below):