How to use the Linux command line to delete files and directories

In this tutorial, we'll show you how to use the rm command and examples illustrate the most common rm option to delete files and directories.

How to delete files

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

Be careful when using the rm command to delete a file or directory, because once deleted files can not be recovered.

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

    rm filename

    If the file is write protected, you will be prompted for confirmation, as shown below. Y Delete a file type and click Enter. Otherwise, if the file is not write-protected, it will be deleted without prompting.

    rm: remove write-protected regular empty file 'filename'?
  • To delete multiple files, use the rm command followed by the file name, separated by a space.

    rm filename1 filename2 filename3

    You can also use wildcards (*) and conventional extension to match multiple files. For example, to delete all .pdf files in the current directory, use the following command:

    rm * .pdf

    When you use rm wildcard (*) and conventional extension, it is recommended to use the ls command to list files, so you can see deleted files before running the rm command.

  • Use this option -i confirmation before deleting each file:

    rm -i filename(s)
    • To delete a file without prompting, even if the file is write-protected, you can use the -f (force) option:
    rm -f filename(s)
  • You can also combine rm options. For example, to delete all .txt files in the current directory and does not prompt the verbose mode, use the following command:

    rm -fv *.txt

    How to delete the directory (folder)

    • To delete an empty directory, use the -d option.
    rm -d dirname
  • To remove a non-empty directory and all files, use the r (recursive) option.

    rm -r dirname

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

    • To remove a non-empty directory and all files without prompting, use the r (recursive) and the -f option.
    rm -rf dirname
  • To delete multiple directories, use the rm command, followed by the directory name separated by a space.

    rm -r dirname1 dirname2 dirname3

    The same file, you can also use wildcards (*) and conventional extension to match multiple directories.

    in conclusion

    By now, you should have a good understanding of how to use Linux rm command, and should be able to use the command line to securely delete files and directories.

Guess you like

Origin www.linuxidc.com/Linux/2019-08/159879.htm