How to delete files and directories using Linux command line

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

Be especially careful when deleting files or directories using the command rmbecause once the file is deleted, it cannot be restored.

In this article, we will show you how to use the rm command to delete files and directories in Linux with examples and explanations of the most common rm options.

  • To delete a single file, use the command rmfollowed by the filename:
    rm filename

    If the file is write-protected, you will be prompted to confirm it as shown below. To delete the file enter y and press 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 at once, use the command rmfollowed by the filenames, separated by a space.
    rm filename1 filename2 filename3

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

    rm *.pdf

    When do you use rm with wildcards ( *) and regular extensions, it is recommended to list the files using the command lsso you can see what files are going to be removed before running the command rm

  • Use the option -i to confirm each file before deleting:
    rm -i filename(s)
  • To delete files without prompting, even if the files are write-protected, use the parameter -f(force):
    rm -f filename(s)
  • You can also combine options rm… For example, to delete all files .txt in the current directory without prompting in verbose mode, use the following command:
    rm -fv *.txt
  • To remove empty directory use this option -d
    rm -d dirname
  • To remove non-empty directories and all files within them, use the option r (recursive).
    rm -r dirname

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

  • To remove non-empty directories and all files without prompting, use r (recursive) and parameter -f
    rm -rf dirname
  • To remove multiple directories at once, use the command rmfollowed by the directory names, separated by spaces.
    rm -r dirname1 dirname2 dirname3

    Same as in files, you can also use the wildcard ( *) and regular expressions to match multiple directories.

By now, you should have a good understanding of how to use the command rm on Linux and you should learn how to safely delete files and directories using the command line.

Please disable your ad blocker or whitelist this site!

Related Posts