Skip to content
shellhacks.dev
Command Line

Delete a File with Special Characters in Its Name

Delete a file whose name holds a question mark, a newline or a leading dash by selecting it with find -inum and -delete. The ls inode option prints the number.

1 min read
Summarize in AI

A file has a name you cannot type or that the shell expands, such as report?.txt or a name with a newline, and rm will not take it.

Shell
touch -- 'report?.txt' '-rf' $'two\nlines'
ls -i
inode=$(ls -i -- 'report?.txt' | cut -d' ' -f1)
find . -maxdepth 1 -inum "$inode" -print -delete
find . -maxdepth 1 -name '-rf' -delete
find . -maxdepth 1 -name $'two*' -delete
ls -A
Text
2902610 -rf
2902609 report?.txt
2902611 two
lines
./report?.txt

Every name in a directory points to an inode number, and ls -i prints it. find . -maxdepth 1 -inum N -delete selects the file by that number, so no quoting is involved at all. The run also removed -rf by name, because find takes it as the argument of -name and not as an option, and used an ANSI-C quoted pattern for the name with a newline. -maxdepth 1 keeps the search to the current directory. See Deleting Files in the findutils manual.

An inode number is only unique within one file system, and hard links share it, so -inum deletes every link inside the searched tree. List with -print before adding -delete. For a leading dash alone, rm -- -rf or rm ./-rf is simpler.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.