Welcome to maniacmartin, the personal site of Martin Smith.
I'm listening to The Gap Band – You Dropped A Bomb on Me

I'm cycling the length of the UK (1000 miles) for charity. Sponsor me now!


    4 October 2007

    Wildcard Parsing in Linux Shells

    Filed under: Computer — martin @ 10:11 pm

    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 mogrify -resize 640x *.jpg
    on a folder containing beach.jpg, pc.jpg and college.jpg, the shell will rewrite that as
    mogrify -resize 640x beach.jpg college.jpg pc.jpg

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

    Now let us consider a folder with the following files: -r foo.bar foofolder barfolder
    where foofolder and barfolder are folders. Issuing a rm *, might, at first glance just delete the files and not the folders. But alas this is expanded to
    rm -r foo.bar foofolder barfolder
    and rm recieves these options -r foo.bar foofolder barfolder
    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.

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

    1 Comment »

    1. I remember reading about how you can use this quirk to your advantage: for example, stick a file with name ‘-i’ in a directory full of irreplaceable files, and rm will run in interactive mode and prompt you to confirm all deletions. Not something I’d rely on, though, I have to say…

      Comment by David — 6 October 2007 @ 2:44 pm

    RSS feed for comments on this post. TrackBack URL

    Leave a comment