How to Remove Files in Linux Terminal?

In this tutorial you will understand, how to use the rmunlink and rmdir commands to delete files in Linux.

How to Remove Files

You can use rm (remove) or unlink command to remove or delete a file from the Linux command line.

The rm command allows you to remove multiple files at once. With unlink command, you can delete only a single file.

While removing files or directories you should be extra careful, as if the file is deleted, you won’t be able to recover it easily.

  • Use the rm or unlink command to delete a single file followed by the file name:

unlink /home/admin/directoryname myfile

rm /home/admin/directoryname/myfile

You will be notified for confirmation if the file is write-protected, as shown below. Type y and hit Enter key to remove the file, or else, it will be deleted without prompting if the file is not write-protected.

Output:

rm: remove write-protected regular empty file ‘file’?

 

  • Use the rm command to delete multiple files at once followed by the file names separated with space:

rm /home/admin/directoryname/myfile1

rm /home/admin/directoryname/myfile2

rm /home/admin/directoryname/myfile3

OR

cd /home/admin/directoryname

rm myfile1 myfile2 myfile3

OR

rm /home/admin/directoryname/myfile*

To match multiple files, you can use an asterisk (*) and regular expansions. Execute the following command to remove all .pdf files placed in the current directory:

rm /home/admin/directoryname/*.pdf

Run the ls command to list the files if you are using regular expansions so that you can see what files will be deleted before running the rm command.

  • Run the rm command with the -i option to verify each file before deleting it:

rm -i /home/admin/directoryname/myfile(s)

 

  • You can run the -f (force) option with rm command to remove the files without prompting even if the files are write-protected:

rm -f /home/admin/directoryname/myfile(s)

 

  • You can also combine rm options. You can run the following command to delete all .txt files in the present directory without a prompt in verbose mode.

rm -fv /home/admin/directoryname/*.txt