How to Remove Files and Directories in Linux Command Line

Remove-Files-Directories-Linux

How to delete a file in Linux? How to delete a directory in Linux? Let’s see how to do both of these tasks with one powerfull command called rm.In this tutorial we can check how to safely delete files and directories using Linux Command line.

How to Remove Files

Open your terminal either by using the Ctrl+Alt+T keyboard shortcut or by clicking on the terminal icon.

To remove (or delete) a file or directory in Linux from the command line, use the rm (remove) command.

Please be very careful when removing files or directories with the rm command, because once the file is deleted it cannot be recovered.

To delete a single file use, the rm command followed by the file name:

If the file is write protected you will be prompted for confirmation as shown below. To remove the file type y and hit Enter. Otherwise, if the file is not write protected it will be deleted without prompting.

To delete multiple files at once use the rm command followed by the file names separated by space:

You can also use a wildcard (*) and regular expansions to match multiple files. For example to remove all .jpg files in the current directory, use the following command:

When you use rm with wildcards (*) and regular expansions, it is recommended to list the files with the ls command so that you can see what files will be deleted before running the rm command.

Use the -i option to confirm each file before deleting it:

To remove files without prompting even if the files are write-protected use the -f (force) option:

You can also combine rm options. For example, to remove all .pdf files in the current directory without a prompt in verbose mode, use the following command:

How to Remove Directories (Folders)

To remove an empty directory use the -d option.

To remove non-empty directories and all the files within them, use the r (recursive) option.

If a directory or a file within the directory is write-protected, you will be prompted to confirm the deletion.

To remove non-empty directories and all the files without being prompted use the r (recursive) and -f options.

To remove multiple directories at once, use the rm command followed by the directory names separated by space.

Identical as with files you can also use a wildcard (*) and regular expansions to match multiple directories.

Congratulations! In this tutorial, we explained the necessary steps to safely remove files and directories on your computer using the command line. You now understand how to use the Linux rm command and you should be able to delete or remove files and directories using the command line.

Leave a Reply

Your email address will not be published. Required fields are marked *