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.
1 2 3 4 5 6 7 8 9 10 |
$ 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.
1 2 |
$ 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.
1 2 |
$ 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.
1 2 |
$ rm -foo rm: invalid option -- 'o' |
Instead, try adding ./
to the filename.
1 2 |
$ rm -v ./-foo removed './-foo' |
Delete File by Adding --
To delete a file with hyphen, you can also use the following syntax.
1 2 |
$ 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.
1 2 3 4 |
$ 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.
1 2 3 4 5 6 7 8 |
$ find . -inum 1833174 -exec rm -v {} \; removed './$foo' $ find . -inum 1833181 -exec rm -v {} \; removed './*foo' $ find . -inum 1833515 -exec rm -v {} \; removed './&foo' |