Linux Delete All Files In Directory
The procedure to remove all files from a directory:
- Open the terminal application
- To delete everything in a directory run: rm /path/to/dir/*
- To remove all sub-directories and files: rm -r /path/to/dir/*
- To remove non-empty directories and all the files: rm -rf dirname
Let us see some examples of rm command to delete all files in a directory when using Linux operating systems.
How to remove all the files in a directory?
Suppose you have a directory called /home/vivek/data/. To list files type the ls command:
$ ls ~/data/
To delete all files in a directory named /home/vivek/data/, run:
$ rm /home/vivek/data/*
You can see what is being done when deleting all files in directory pass the -v option to the rm command:
$ rm -v /home/vivek/data/*
Verify using the ls command:
$ ls -l /home/vivek/data/
As you can see rm command failed to remove subdirectories /home/vivek/data/images and /home/vivek/data/scripts. To delete all files folders from a directory, run:
$ rm -rfv /home/vivek/data/
Understanding rm command option that deleted all files in a directory
- -r : Remove directories and their contents recursively.
- -f : Force option. In other words, ignore nonexistent files and arguments, never prompt. Dangerous option. Be careful.
- -v : Verbose option. Show what rm is doing on screen.
Deleting hidden vs non-hidden files
Bash remove all files from a directory including hidden files using the dotglob option
If the dotglob option set, bash includes filenames beginning with a ‘.’ in the results of pathname expansion. In other words, turn on this option to delete hidden files:
# Bash shell and may not work on other shells # Turn on dotglob (set) # shopt -s dotglob # Remove all files including hidden .files # rm -v ~/project/oldfiles/* rm -vrf ~/project/oldfiles/* # Turn off dotglob (unset) # shopt -u dotglob
See GNU/bash man page for the shopt command online here:
Linux Remove All Files In Directory
As I said earlier one can use the unlink command too. The syntax is:
For example, delete file named foo.txt in the current working directory, enter:
It can only delete a single file at a time. You can not pass multiple files or use wildcards such as *. Therefore, I strongly recommend you use the rm command as discussed above.