July 14, 2021 . 3 MIN READ
https://www.cyberciti.biz/faq/linux-delete-all-files-in-directory-using-command-line/
The procedure to remove all files from a directory:
Let us see some examples of rm command to delete all files in a directory when using Linux operating systems.
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/
In Linux, any file or directory that starts with a dot character called a dot file. It is to be treated as hidden file. To see hidden files pass the -a to the ls command:
ls
ls -a
ls -la
To remove all files except hidden files in a directory use:
rm /path/to/dir/*
rm -rf /path/to/dir/*
rm *
In this example, delete all files including hidden files, run:
rm -rf /path/to/dir1/{*,.*}
rm -rfv /path/to/dir1/{*,.*}
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:
man bash
help shopt
As I said earlier one can use the unlink command too. The syntax is:
unlink filename
For example, delete file named foo.txt in the current working directory, enter:
unlink foo.txt
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.
In this quick tutorial, you learned how to remove or delete all the files in a directory using the rm command. Linux offers a few more options to find and delete files. Please see the following tutorials: