Wildcard Parsing in Linux Shells

I have just discovered a quirk in linux shells.

When you issue a command with a wildcard, bash will replace the wildcard with a list of matching files. So when you type <code>mogrify -resize 640x *.jpg</code>
on a folder containing beach.jpg, pc.jpg and college.jpg, the shell will rewrite that as
<code>mogrify -resize 640x beach.jpg college.jpg pc.jpg</code>

and mogrify is given the options <code>-resize 640x beach.jpg college.jpg pc.jpg</code> (filenames in alphabetical order)

Now let us consider a folder with the following files: <code>-r foo.bar foofolder barfolder</code>
where foofolder and barfolder are folders. Issuing a <code>rm *</code>, might, at first glance just delete the files and not the folders. But alas this is expanded to
<code>rm -r foo.bar foofolder barfolder</code>
and rm recieves these options <code>-r foo.bar foofolder barfolder</code>
In fact, only the -r file will survive.

OK, you say, but who has files beginning with hyphens? Well, it could happen. And some commands, like tar, dont need a hyphen at the beginning of their arguments.

<blockquote>martin@xenon:~/tests$ ls
folder -r
martin@xenon:~/tests$ rm *
martin@xenon:~/tests$ ls
-r</blockquote>

Posted 4th October 2007 in Computer, with 1 comment

Digg!