Linux: How to delete files with odd names safely

An annoying problem using the rm command is how to delete files with odd names, with odd names we mean files with spaces, control…

Linux: How to delete files with odd names safely
Photo by Gabriel Heinzer on Unsplash

An annoying problem using the rm command is how to delete files with odd names, with odd names we mean files with spaces, control characters, files starting with dash etc, trying to delete them with wildcards can be a dangerous practice especially if we use the -f option. In this article i will show you how you can safely delete such files.

Create a file with an odd name

Open a terminal and run the following command, this will create a file starting with “-”

echo "" > -file.txt

Try to delete the file

Lets try now to delete the file using the rm command

rm -file.txt  
rm: illegal option -- l 
usage: rm [-f | -i] [-dIPRrvWx] file ... 
       unlink [--] file

As we can see the rm command fails because bash interprets the dash in the file as parameters

Delete the file the correct way

To delete the file we need to use a trick!. Each file in a Linux file system has an inode which is a unique integer that points to metadata specific to the file. We can find a file inode number using the ls command

ls -il 
total 16 
4169949 -rw-r--r--   1 kpatronas  staff     1 Aug 29 16:55 -file.txt 
 373126 drwx------@  7 kpatronas  staff   224 Aug 28 17:31 Applications 
 251264 drwx------+  4 kpatronas  staff   128 Aug 25 19:53 Desktop

The number to the left of each line is the inode number, which in file -file.txt is 4169949. To delete a file using the inode number we can use the find command

find <mount-point> -inum <inode-number> -exec rm {} \;

In our case this translates to

find . -inum 4169949 -exec rm {} \;

Checking with ls we can verify that the file deleted.

Renaming the file

Deleting might not be always the desired action, we might want just to rename the file to something more handy. To do this we use the find command again with the mv option now.

find <mount-point> -inum <inode-number> -exec mv {} <new-filename> \;

In our case this translates to

find . -inum 4169949 -exec mv {} something_normal.txt \;

Checking with ls we can verify that the file has been renamed.

Conclusion

In this article we saw how to deal with files in the edge case that we have files with odd names, we saw how we can use ls with find to delete or rename such files to something more handy! i hope you found this article easy to understand and help you to deal with such problems :)

Join Medium with my referral link - Konstantinos Patronas
As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…