Globbing

From NetBSD Wiki

Jump to: navigation, search
This article is a stub. You can help by editing it.

Globbing is also called wildcard expansion. Most, if not all, Unix shells have the facility to expand certain "special characters" into a list of files, as a way of abbreviating them. It's easiest to understand by an example:

$ ls
foo bar baz qux quux qwux mumble mutter
$ echo f*
foo
$ echo b*
bar baz
$ echo q?ux
quux qwux
$ echo q*ux
qux quux qwux

Most shells have the two basic globbing characters from the example, * and ?. The first (the asterisk, or *) matches zero or more arbitrary characters (compare with regex .*), while the second (the question mark, or ?) matches exactly one arbitrary character. These were standardised by the Bourne shell, but the C shell uses them also. Other shells include a variety of different globbing characters.

Note: programs which only accept one positional argument don't accept globs, since globs are expanded by the shell even before the program sees them. The program only sees the expansion of the globs. See the next section for more information.

The difference with DOS

In DOS and its derivatives, we also see the basic globbing characters (* and ?) appear sometimes. It can be useful to know the difference between Unix shell globs and DOS wildcards. In DOS, the * and ? characters are passed as-is to the program, where under Unix the files are replaced by the shell and the results are passed to the program. That is, the following program works differently in Unix than it does in DOS:

#include <stdio.h>
int main(int argc, char *argv[])
{
         for (int i = 1; i < argc; ++i)
                 printf("Argument %i: %s\n", argc, argv[i]);
        return 0;
}

In Unix, the output looks like this (using the above directory contents):

$ ./prog f* b* q?ux
Argument 1: foo
Argument 2: bar
Argument 3: baz
Argument 4: quux
Argument 5: qwux

In DOS, the output would look like this:

$ PROG F* B* Q?UX
Argument 1: F*
Argument 2: B*
Argument 3: Q?UX

That's right, DOS doesn't really do wildcard expansion. Every single program has to implement this individually.

See also

Personal tools