/bin/sh: Delete files with weird characters in Unix

I recently used “tar” improperly and inadvertently created a file which seemed near impossible to delete. The file started with two dashes; it was named –exclude.tgz. I issued each of the following commands with no luck:

boudreaux:~ # rm --exclude.tgz
rm: unrecognized option <code>--exclude'
Try
rm –help’ for more information.

boudreaux:~ # rm “–exclude.tgz”
rm: unrecognized option --exclude'
Try
rm –help’ for more information.

boudreaux:~ # rm “\–exclude.tgz”
rm: unrecognized option --exclude'
Try
rm –help’ for more information.

boudreaux:~ # rm *tgz [it was the only tarball in the directory]
rm: unrecognized option --exclude'
Try
rm –help’ for more information.

I was just about fed up so I messaged my friend Larry, a Unix administrator, to ask for help. He initially recommended some of the above techniques but, as you can see, each of them failed. He then gave me this magical command which instantly worked

find . -name \*.tgz -exec rm {} \;

Oh, years later, I found this to work, too:

rm <code>find .|grep exclude

Perfect!

Chrissy is a Cloud and Datacenter Management & Data Platform MVP who has worked in IT for over 20 years. She is the creator of the popular SQL PowerShell module dbatools, and holds a number of certifications, including those relating to SQL Server, Linux, SharePoint and network security. You can follow her on Twitter at @cl.

Posted in Linux
2 comments on “/bin/sh: Delete files with weird characters in Unix
  1. krishna says:

    Hi,
    This way you will remove all tgz found in your dir, including sub dirs!

    Try the full path “rm ./–exclude.tgz”.

    bye

  2. Russell says:

    Full or partial path works, also the — option to rm (to end option parsing), like

    rm — –exclude.tgz

Leave a Reply

Your email address will not be published. Required fields are marked *

*