linux

fatmawati achmad zaenuri/Shutterstock.com

The rm command lets you delete a file or directory passing its name: “rm filename” or “rm -d directory.” You can include a directory path, too. If there are files in the directory, use the -r option “rm -r directory” to delete files and folders recursively.

The Linux rm command deletes files and directories. To use this tool safely, you need to be certain what’s going to happen when you hit “Enter.” Here’s what you need to know.

What Is the rm Command in Linux?

The Linux rm command is primarily for deleting files. It’s one that most people encounter soon after they start using Linux. Just by virtue of being a newcomer to Linux, you’re likely to make mistakes. You’ll create or copy files by accident, or with the wrong name, or to the wrong place. It’s all part of the learning curve of the command line. The clean-up operations for such mistakes involve rm .

The rm command can delete files, groups of files, directories, or complete directory trees. That’s why it must be used with caution. Using rm isn’t difficult, but the penalty for failure is high.

When a file is deleted with rm , it is gone. It isn’t moved to the trash. It is obliterated immediately. That doesn’t mean you should avoid using rm . But to use it safely, you need to be aware of what it can do, and ensure you’re using it properly.

Some tools are more dangerous than others, and far less forgiving of mistakes. That’s why there’s never been a movie called The Texas Wrench Massacre. rm isn’t a wrench, it’s definitely a chainsaw.

People use chainsaws all day everyday, and as long as they use one responsibly and mindfully, they’re fine. It’s the same deal with rm . When you pull rm out of your tool bag, you ought to slow down and check, then double-check, your command line.

The rm command is an executable, it’s not part of the shell. So, although we’re using Bash here, it’s the standard Linux rm, not a special Bash rm.

How to Delete Files With rm

The simplest way to use rm is to provide the name of a file you want to delete.

rm config.gc

linux

You’re silently returned to the command line. rm adopts the classic, close-lipped Linux stance that if it doesn’t complain about anything, you can assume it did what you asked. Providing a filename like this causes rm to look for the file in the current working directory.

You can provide multiple file names on the command line. You can also provide a directory path if a file you want to delete isn’t in the current directory.

rm memlog.sh /home/dave/dev-archive/config.gc

linux

Again, nothing is reported if rm manages to delete the specified files.

Using Wildcards With rm

Wildcards allow you to specify groups or collections of files without having to list the individual files on the command line.

The asterisk “*” represents any sequence of characters, including none. The question mark “?” represents any single character.

To check that your wildcards are going to match what you expect them to, and nothing more, you can use them with ls before you use them with rm.

To delete all of the PNG files in the current directory, use “*.png.” This means any sequence of characters followed by “.png” will be matched. When the files have been deleted, we can use ls to verify that they’ve gone.

ls *.png
rm *.png
ls *.png

linux

On our test computer, we’ve got two files in the current directory with names starting with “config.”

We’re able to delete both of these by using the asterisk wildcard. It matches both files because rm is looking for filenames that start with “config”, followed by any sequence of characters. On one file, that sequence of characters is “.sl3”, the filename extension. The other filename has no characters after “config”, but because the asterisk matches any characters or no characters, it matches that filename too.

ls config*
rm config*
ls config*

linux

You can use the question mark in pairs. This will delete files that have file extensions of two characters exactly.

ls *.??
rm *.??
ls *.??

linux

Using rm Interactively

A safe way to use rm is to force it to ask for confirmation before it deletes each file. The -i (interactive) option lets you do this. When you add this option to your command line, rm will prompt you before each deletion, giving you a chance to step over actions you hadn’t intended.

We’ll use the -i (interactive) option in this command. It tries to delete all files with a single character file extension.

rm -i *.?

linux

Each matching file is presented in turn. If you answer “y” or “Y” the file is deleted. If you answer “n”, the file is retained. In fact, if you answer with anything other than “y” or “y”, the file is retained. You can just hit “Enter” and the file is retained.

You can quickly work through your list of files, deleting or skipping over files to cherry-pick the ones you want to remove. As we’ll see you can use the i- (interactive) option with other rm options.

Linux Commands
Files tar · pv · cat · tac · chmod · grep ·  diff · sed · ar · man · pushd · popd · fsck · testdisk · seq · fd · pandoc · cd · $PATH · awk · join · jq · fold · uniq · journalctl · tail · stat · ls · fstab · echo · less · chgrp · chown · rev · look · strings · type · rename · zip · unzip · mount · umount · install · fdisk · mkfs · rm · rmdir · rsync · df · gpg · vi · nano · mkdir · du · ln · patch · convert · rclone · shred · srm · scp · gzip · chattr · cut · find · umask · wc
Processes alias · screen · top · nice · renice · progress · strace · systemd · tmux · chsh · history · at · batch · free · which · dmesg · chfn · usermod · ps · chroot · xargs · tty · pinky · lsof · vmstat · timeout · wall · yes · kill · sleep · sudo · su · time · groupadd · usermod · groups · lshw · shutdown · reboot · halt · poweroff · passwd · lscpu · crontab · date · bg · fg · pidof · nohup · pmap
Networking netstat · ping · traceroute · ip · ss · whois · fail2ban · bmon · dig · finger · nmap · ftp · curl · wget · who · whoami · w · iptables · ssh-keygen · ufw · arping · firewalld

Using the rm Force Option

If you try to delete a file that is read-only, rm prompts you for confirmation before it deletes the file. That’s a good safety net, but one that could become tedious if you have a lot of files to delete.

rm geonames.sl3

linux

The -f (force) option instructs rm to never prompt. You’re telling it “Yes, delete all files that you would normally prompt me about.” It also prevents rm from complaining about non-existent files.

rm -f geonames.sl3

linux

The -f (force) option is often used when you’re deleting a nested set of files and directories.

Deleting Directories With rm

The rm command can optionally remove directories too, along with the files they contain. This is similar to the rmdir command, but rmdir cannot delete directories with files in them. It only deletes empty directories. The rm command can easily delete directories that contain files and other directories.

Deleting a directory is similar to deleting a file. We provide the name of the directory on the command line. We need to include the -d (directory) option. Like we did when we were deleting files, we can provide the name of several directories. We can provide a path to directory that is not in the current working directory.

rm -d old-projects

linux

If the directory contains files, this will fail.

To delete a directory and its contents, use the -r (recursive) flag. This deletes the directory, its files, and any nested directories it contains.

rm -d archive
rm -r archive

linux

The second command succeeds.

To switch rm into full-on chainsaw mode, we can combine the -r (recursive) and -f (force) options. This tells rm to recursively delete all files and directories in a directory tree, even if they are read-only, and without ever prompting us.

On our test computer, we’ve got a directory called “migrated code.” It contains files and another directory called “6502.” The “6502” directory also contains files and another directory called “ASM.” There’s files in that directory, too. Some of the files are read-only.

We’ll also include the -v (verbose) command so that rm tells us what it is doing.

rm -rfv migrated-code

linux

In the output we can see that the files are removed and, when they’re empty, the directories are removed too.

linux

Avoiding Mistakes When Using rm

Spaces and other weird characters in filenames can present problems. Filenames that start with a hyphen “-” for example, can be mistaken for command line options. If we have a file called “-contributors.txt”, rm will try to process the name as a sequence of command line options.

Because rm doesn’t have an option called “-c“, the command line parsing fails and the file isn’t deleted. To delete the file you need to precede it with “./” to provide a path to it.

rm -contributors.txt
rm ./-contributors.txt

linux

Spaces in filenames are also problematic. Either quote the entire filename, or use tab completion to insert the name of the file onto the command line for you, escaping the spaces as it does so. If you don’t use either of these options, rm will treat each portion of the filename as an individual file.

Here, we’ve got two files, one called “backup” and one called “backup to delete.” We can demonstrate the problem with these file names, using ls. If we try to use ls on the “backup to delete” file and we don’t escape or quote the file name, the command fails.

ls -hl backup to delete

linux

ls complains that it can’t find files called “to” or “delete”, but it does find a file called “backup.” That’s what rm will do, too. It’ll complain about two missing files, and it’ll then delete the file called “backup”, which isn’t what we wanted.

rm backup to delete

linux

rm thinks it is working with three files, “backup”, “to”, and “delete.” It complains that it can’t find “to” and “delete”, but it finds and silently deletes “backup.”

Quoting the filename allows rm to delete the correct file.

rm 'backup to delete'

linux

You could also escape the spaces with backslashes ““, like this:

rm backup to delete

linux

If you use tab completion to enter your filenames, they’ll be automatically escaped, if required.

What PPE?

Unlike real-world chainsaws, there’s no personal protective equipment you can use with rm.

What you can do, is check your syntax with ls before you try it with rm, and use the interactive mode so that you get to decide what gets deleted.

Other than that, it’s practice until you feel comfortable and confident. The safest way to do that is to copy a bunch of sacrificial files to a directory and practice on those.

TECH NEWS RELATED

A Twisted New Body Dysmorphia Romantic Film Looks Gruesomely Unique

Some movie trailers do their best to push all the information you might need before the premiere to let you properly gauge your interest. Other trailers don’t care about all that and only want to show you a series of odd sequences you cannot piece together, but know you’ll ...

View more: A Twisted New Body Dysmorphia Romantic Film Looks Gruesomely Unique

How to Disable Screenshot Thumbnail Previews on Mac

Modern versions of macOS feature a floating thumbnail preview for screenshots that allows users to quickly apply edits to their screenshots before they save them. If you find this interface too obtrusive, or simply prefer to edit your screenshots later using the Preview app, Here is how you can ...

View more: How to Disable Screenshot Thumbnail Previews on Mac

LG’s smart projector is the square cousin of Samsung’s cool The Freestyle

This Tiny MSI PC is Packed With Power

MSI Following the example set by the Mac Mini, many Windows-powered compact PCs have popped up recently with solid hardware. If none have quite caught your eye, though, maybe this PC by MSI will. MSI has just released a new tiny PC called the Cubi 5 12M, and it’s ...

View more: This Tiny MSI PC is Packed With Power

Logitech’s New Colorful Keyboards and Mice Look Great

Logitech Logitech makes some of the best keyboards and best mice around, and you might be familiar with the company’s RGB-packed gaming products. These new peripherals are really packed with color, but we’re not really talking about lights. Logitech has announced a range of new colors for a bunch ...

View more: Logitech’s New Colorful Keyboards and Mice Look Great

“Part of the Journey Is the End;” Marvel’s Avengers Seems to be Shutting Down

Whether it be purely the lackluster quality of the game or the general distaste for live service games, Marvel’s Avengers never truly found its footing in the two years since it was released. Despite the fact that both the Marvel and Avengers labels should guarantee a happy, comic-lover audience, ...

View more: “Part of the Journey Is the End;” Marvel’s Avengers Seems to be Shutting Down

How To Find Your Laptop IP Address

Most internet-related problems can be solved with the knowledge of the IP address. Your Internet Protocol (IP) address can be very helpful when you are trying to narrow down the error source. Network troubleshooting is also made easy with the IP address code. There have been several issues where it ...

View more: How To Find Your Laptop IP Address

How To Snip Screen On Your Laptop?

Taking a screenshot is not a complicated process. All of us are familiar with at least one way to do it. However, there are several ways to capture your screen for a frame. We made this article to show you all the different ways you can grab your screens. If ...

View more: How To Snip Screen On Your Laptop?

How To Connect AirPods To A Laptop?

Satechi Thunderbolt 4 Slim Hub review: A sleek and portable laptop hub

Wi-Fi routers are being hit by a dangerous new Android malware with extra DNS hacks

Fix CAA20004 Microsoft Teams Sign in Error

How To Fix This Update Is Not Applicable To Your Computer Error: 11 Quick Fixes

Servant unleashes a bed bug blitz [Apple TV+ recap]

Hostinger quietly shutters Zyro to focus on Hostinger Website Builder service

Redmi Note 12 Turbo Tipped to get Snapdragon 7-series SoC

How to customize and publish a Microsoft Bookings page?

Avatar 2 animators tricked James Cameron into believing some shots were practical

Super Bowl 2023 live stream: how to watch the game, commercials and halftime show from anywhere

The Minecraft Community Answers the Age-old Question: “Can it Run Doom?”

OTHER TECH NEWS

Top Car News Car News