Unix / Linux: Delete File with Special Characters

Objective: Delete a file with names that contain spaces and/or special characters such as hyphen (-), semicolon (;), ampersand (&), dollar sign ($), question mark (?), asterisk (∗), etc.

Let’s look at the files that we want to delete below.

$ ls -l
total 0
-rw-rw-r-- 1 ibrahim staff 0 Jul 10 17:13 foo
-rw-rw-r-- 1 ibrahim staff 0 Jul 10 17:13 >foo
-rw-rw-r-- 1 ibrahim staff 0 Jul 10 17:15 -foo
-rw-rw-r-- 1 ibrahim staff 0 Jul 10 17:15 --foo
-rw-rw-r-- 1 ibrahim staff 0 Jul 10 17:16 $foo
-rw-rw-r-- 1 ibrahim staff 0 Jul 10 17:16 *foo
-rw-rw-r-- 1 ibrahim staff 0 Jul 10 17:16 &foo
-rw-rw-r-- 1 ibrahim staff 0 Jul 10 17:16 foo bar

Now, let’s look at how we can delete those files.

Delete File with Quotes

For file name with spaces, using quotes will help.

$ rm -v "foo bar"
removed 'foo bar'

Delete File with Backslash

You can insert a backslash (\) before a space or special character in the filename.

$ rm -v foo\ bar
removed 'foo bar'

Delete File by Adding ./

If you try deleting a file with a hyphen in front, you will get an error.

$ rm -foo
rm: invalid option -- 'o'

Instead, try adding ./ to the filename.

$ rm -v ./-foo
removed './-foo'

Delete File by Adding --

To delete a file with hyphen, you can also use the following syntax.

$ rm -v -- --foo
removed '--foo'

Delete File with Inode Number

To get the inode number of a file, use ls with -i option. The first column contains the inode number.

$ ls -li
1833174 -rw-rw-r-- 1 ibrahim staff 0 Jul 10 17:16 $foo
1833181 -rw-rw-r-- 1 ibrahim staff 0 Jul 10 17:16 *foo
1833515 -rw-rw-r-- 1 ibrahim staff 0 Jul 10 17:16 &foo

Use the find command to delete the file using the inode number.

$ find . -inum 1833174 -exec rm -v {} \;
removed './$foo'

$ find . -inum 1833181 -exec rm -v {} \;
removed './*foo'

$ find . -inum 1833515 -exec rm -v {} \;
removed './&foo'

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, perl, php, python, java, javascript, nodejs, angular, react); plays_on(xbox, ps4); linux_desktop_user(true); }