How to – Remove Files and Directories Using Linux Command Line
In this tutorial, we will see how to use the rm, unlink, and rmdir commands to remove files and directories in Linus using Terminal (command line).
Remove Files:
To remove (or delete) a file on Linux using the command line, use either rm (remove) or unlink command.
unlinkcommand allows you to remove only a single file.rmcommand allows you to remove multiple files at once.
Caution: Be extra careful while removing files or directories, because once the file/s is deleted it cannot be easily recovered.
Examples:
- To delete a single file, use the
rmorunlinkcommand followed by the file name:unlink filenamerm filenameIf the file is write-protected, you will be prompted for confirmation, see below.
rm: remove write-protected regular empty file 'filename'?To remove the file typey, and hitEnter. Otherwise, if the file is not write-protected, it will be deleted without prompting. - To delete multiple files at once, use the
rmcommand followed by file name/s . Each file name is separated by space.rm filename1 filename2 filename3You can use wildcard as-trick (
*) and regular expansions to match multiple files. For example, to remove all.txtfiles in the current directory, use the following command:rm *.txtNote: Always use the ls command to first list/ see the files you are about to delete when using regular expressions
rmcommand with the-ioption is used to confirm each file before deleting it:rm -i filename(s)-
rmcommand with the-f(force) option us used to remove files without prompting, even if the files are write-protected.rm -f filename(s) - You can also combine
rmoptions. For example, to remove all.txtfiles in the current directory without a prompt in verbose mode, use the following command:rm -fv *.txt
Remove Directories (Folders):
In Linux, you can remove /delete directories using the rmdir and rm commands as below.
rmdir is a command-line utility for deleting empty directories, while with rm you can remove directories and their contents recursively.
- To remove an empty directory, use either
rmdirorrm -dfollowed by the directory name:rm -d dirnamermdir dirname - To remove non-empty directories and all the files within them, use the
rmcommand with the-r(recursive) option:rm -r dirnameIf 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
rmwith the-r(recursive) and-foptions:rm -rf dirname - To remove multiple directories at once, use the
rm -rcommand followed by the directory names separated by space.rm -r dirname1 dirname2 dirname3Same as with files, you can also use a wildcard (
*) and regular expansions to match multiple directories.
Feel free to leave a comment if you have any questions.