arrow-left arrow-right brightness-2 chevron-left chevron-right circle-half-full dots-horizontal facebook-box facebook loader magnify menu-down rss-box star twitter-box twitter white-balance-sunny window-close
Find and the importance of parameters order
2 min read

Find and the importance of parameters order

Parameter order matters. Especially in commands such as find. This post covers a common problem using find when deleting files and some tips to avoid it.
Find and the importance of parameters order

Someone texted me with this tweet a few weeks ago. It made me remember how important the order of the parameters in some commands could be. Let's see the tweet.

As you may have noticed, some commands, such as find, take its parameters in order. So, this command:

find -type f -delete -name contents.html

is completely different from this another one:

find -type f -name contents.html -delete

The first one says find to look for every regular file and delete it. The second one says to look for every standard file that matches precisely with contents.html and then delete it.

As Tomas says in his tweet, the first one worked, but unfortunately, deleted all files, which could be a mess in a production system.

So, how to avoid this kind of situation?

First of all, mainly when I'm in a production system, I prefer to start typing a «#» as the first character. Why? Because I want to avoid executing an unfinished command by hitting the Enter key by mistake.

Instead of this, I always print the find's output first to ensure that it finds what we need.

find -type f -name contents.html -exec echo {} \;

This command will print the whole list of files which name matches precisely with «contents.html». Once we've ensured the output is ok, then we can delete them.

find -type f -name contents.html -exec rm -f {} \;

Another alternative to this command could be passing the output through a pipe, and then use xargs and rm.

find -type f -name contents.html | xargs rm -f

Now you don't have excuses! Don't forget, parameter order matters. When in production systems, I always try not to be creative.

So memorize the commands you usually use and write their parameters always the same order. Always. Being creative in production is not a good idea. Don't deal with the devil ;-)