rmdir directory not empty in windows & Linux – Code Example

rmdir command is used to remove directories in windows and linux systems but only if they are empty. If the directories are non-empty then you will get the error rmdir directory not empty. Use -r flag to recursively delete all files and folders within the folder you want to delete.

Code Examples

1. Using unlink

Unlink command can be used to delete a single file.

unlink filename

2. Using rm without flags

Similar to unlink, rm command can be used to delete files. If no flag is added then it will delete only the files provided in command. Multiple files could be deleted using this command.

rm file1 file2 file3 file4

3. Using remove for deleting links

remove can be used to delete a file or empty folder. It basically deletes the link. So, for example, you have multiple links to a file and you remove one link, then it won’t delete the file. If all the links are removed then file will be deleted automatically.

Internally, it calls unlink for files and rmdir for directories.

remove file1

4. Using rmdir for empty directories

You can delete empty directories using rmdir command.

rmdir folder1 folder2 folder3

5. Using rm *.extension

You can delete files of same extensions like txt, pdf, docx, xlsx, jpg, etc. using rm command.

rm *.txt
rm *.pdf
rm *.jpg

6. Using rm -i flag to get delete confirmation

Removing files are risky and if you want to check each file before deleting then you can use -i flag.

rm -i *.txt

Using this flag, the output will look like this –

rm: remove regular file 'file1.txt'? y
rm: remove regular file 'file2.txt'? n
rm: remove regular file 'file3.txt'? n
rm: remove regular file 'file4.txt'? y

7. Using rm -f to force delete

-f flag is used to delete write protected files without any confirmation.

rm -f *.txt

8. Using rm -v to get information of all deleted files

If you want to display information of all the deleted files, you can use -v flag.

rm -v *.txt

9. Removing an empty directory using rm -d

Just like rmdir, you can remove an empty directory using -d flag.

rm -d folder1

10. Removing non-empty directory using rm -r

-r flag is used to recursively delete files and folders. It is used for deleting a non-empty folder.

rm -r folder1