/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 PowerShell MVP who has worked in IT for nearly 20 years, and currently serves as a Sr. Database Engineer in Belgium. Always an avid scripter, she attended the Monad session at Microsoft’s Professional Developers Conference in Los Angeles back in 2005 and has worked and played with PowerShell ever since. Chrissy is currently pursuing an MS in Systems Engineering at Regis University and helps maintain RealCajunRecipes.com in her spare time. She holds a number of certifications, including those relating to SQL Server, SuSE Linux, SharePoint and network security. She recently became co-lead of the SQL PASS PowerShell Virtual Chapter. 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 *

*