[Courses][Linux comands] Finding things with locate, find, and grep

Peter Clay pete at flatline.org.uk
Mon Feb 23 11:07:00 EST 2004


(warning: this is pedantic and not nearly as readable as Carla's original
post)

On Mon, 23 Feb 2004, Conor Daly wrote:

> But of course, this is about _linux_ commands and it's so cool that everyone
> else should do it...
> 
> Incidentally, Carla mentioned wildcards with find.  It's important to note
> that the wildcard _must_ be inside single quotes (eg find . -name 'arrow*').
> This protects the wildcard from expansion by the shell before find gets the
> pattern.  Without the quotes, the command will expand to "find . -name
> arrow.png" 'cos you had a file called 'arrow.png' in your home dir and
> nothing else will be found.

Now is probably a good time to mention that find can be both useful and
dangerous in conjunction with xargs:

pete at platinum:~/t$ touch wanted
pete at platinum:~/t$ touch junk.png
pete at platinum:~/t$ touch 'wanted junk.png'
pete at platinum:~/t$ ls -l
-rw-rw-r--    1 pete     pete          0 Feb 23 09:59 junk
-rw-rw-r--    1 pete     pete          0 Feb 23 09:59 wanted
-rw-rw-r--    1 pete     pete          0 Feb 23 09:59 wanted junk.png
pete at platinum:~/t$ find . -name '*.png' | xargs rm
rm: cannot remove `junk.png': No such file or directory
pete at platinum:~/t$ # huh?
pete at platinum:~/t$ ls -l
-rw-rw-r--    1 pete     pete          0 Feb 23 09:59 wanted junk.png

In trying to locate and delete all my .png files, I've deleted something
accidentally (wanted) and not deleted something I wanted to delete ("wanted
junk.png"). UNIX allows spaces in filenames but doesn't always handle them
sensibly. GNU find allows you to dodge this landmine:

pete at platinum:~/t$ find . -name '*.png' -print0 | xargs -0 rm

That command uses null characters as seperators rather than spaces.
For extra bonus security holes, you can put newlines in filenames and
cause mayhem for other people's find commands. For example, it used to be
common to have a cron job to remove 'core' files nightly, something of the
form:

find / -name core | xargs rm

.. running from root's crontab. It is possible to construct some filenames
which will cause that command to remove e.g. /etc/passwd, preventing
anyone from logging into the system. I'm going to leave it as an exercise
for the reader in how to do that.

Pete
-- 
Peter Clay                                         | Campaign for   _  _| .__
                                                   | Digital       /  / | |
                                                   | Rights!       \_ \_| |
                                                   | http://www.ukcdr.org





More information about the Courses mailing list