start page | rating of books | rating of authors | reviews | copyrights

Unix Power ToolsUnix Power ToolsSearch this book

33.4. What if a Wildcard Doesn't Match?

I ran into a strange situation the other day. I was compiling a program that was core dumping. At some point, I decided to delete the object files and the core file, and start over, so I gave the command:

% rm *.o core

It works as expected most of the time, except when no object files exist. (I don't remember why I did this, but it was probably by using !! (Section 30.8) when I knew there weren't any .o's around.) In this case, you get No match, and the core file is not deleted.

It turns out, for C shell users, that if none of the wildcards can be expanded, you get a No match error. It doesn't matter that there's a perfectly good match for other name(s). That's because, when csh can't match a wildcard, it aborts and prints an error -- it won't run the command. If you create one .o file or remove the *.o from the command line, core will disappear happily.

On the other hand, if the Bourne shell can't match a wildcard, it just passes the unmatched wildcard and other filenames:

*.o core

to the command (in this case, to rm) and lets the command decide what to do with it. So, with Bourne shell, what happens will depend on what your rm command does when it sees the literal characters *.o.

The Korn shell works like the Bourne shell.

You can make csh and tcsh act a lot like sh (and ksh) by setting the shell's nonomatch option. Without nonomatch set, the shell sees a nonmatching wildcard and never runs ls at all. Then I set nonomatch and the shell passes the unmatched wildcard on to ls, which prints its own error message:

% ls a*
ls: No match.
% set nonomatch
% ls a*
ls: a*: No such file or directory

In bash Version 1, the option allow_null_glob_expansion converts nonmatching wildcard patterns into the null string. Otherwise, the wildcard is left as is without expansion. Here's an example with echo (Section 27.5), which simply shows the arguments that it gets from the shell. In the directory where I'm running this example, there are no names starting with a, but there are two starting with s. In the first case below, allow_null_glob_expansion isn't set, so the shell passes the unmatched a* to echo. After setting allow_null_glob_expansion, the shell removes the unmatched a* before it passes the results to echo:

bash$ echo a* s*
a* sedscr subdir
bash$ allow_null_glob_expansion=1
bash$ echo a* s*
sedscr subdir

bash Version 2 leaves nonmatching wildcard patterns as they are unless you've set the shell's nullglob option (shopt -s nullglob). The nullglob option does the same thing that allow_null_glob_expansion=1 does in bash version 1.

zsh gives you all of those choices. See the options CSH_NULL_GLOB, NOMATCH and NULL_GLOB.

--ML and JP



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.