1 @node Pattern Matching, I/O Overview, Searching and Sorting, Top
2 @c %MENU% Matching shell ``globs'' and regular expressions
3 @chapter Pattern Matching
5 @Theglibc{} provides pattern matching facilities for two kinds of
6 patterns: regular expressions and file-name wildcards. The library also
7 provides a facility for expanding variable and command references and
8 parsing text into words in the way the shell does.
11 * Wildcard Matching:: Matching a wildcard pattern against a single string.
12 * Globbing:: Finding the files that match a wildcard pattern.
13 * Regular Expressions:: Matching regular expressions against strings.
14 * Word Expansion:: Expanding shell variables, nested commands,
15 arithmetic, and wildcards.
16 This is what the shell does with shell commands.
19 @node Wildcard Matching
20 @section Wildcard Matching
23 This section describes how to match a wildcard pattern against a
24 particular string. The result is a yes or no answer: does the
25 string fit the pattern or not. The symbols described here are all
26 declared in @file{fnmatch.h}.
30 @deftypefun int fnmatch (const char *@var{pattern}, const char *@var{string}, int @var{flags})
31 This function tests whether the string @var{string} matches the pattern
32 @var{pattern}. It returns @code{0} if they do match; otherwise, it
33 returns the nonzero value @code{FNM_NOMATCH}. The arguments
34 @var{pattern} and @var{string} are both strings.
36 The argument @var{flags} is a combination of flag bits that alter the
37 details of matching. See below for a list of the defined flags.
39 In @theglibc{}, @code{fnmatch} might sometimes report ``errors'' by
40 returning nonzero values that are not equal to @code{FNM_NOMATCH}.
43 These are the available flags for the @var{flags} argument:
49 Treat the @samp{/} character specially, for matching file names. If
50 this flag is set, wildcard constructs in @var{pattern} cannot match
51 @samp{/} in @var{string}. Thus, the only way to match @samp{/} is with
52 an explicit @samp{/} in @var{pattern}.
57 This is an alias for @code{FNM_FILE_NAME}; it comes from POSIX.2. We
58 don't recommend this name because we don't use the term ``pathname'' for
64 Treat the @samp{.} character specially if it appears at the beginning of
65 @var{string}. If this flag is set, wildcard constructs in @var{pattern}
66 cannot match @samp{.} as the first character of @var{string}.
68 If you set both @code{FNM_PERIOD} and @code{FNM_FILE_NAME}, then the
69 special treatment applies to @samp{.} following @samp{/} as well as to
70 @samp{.} at the beginning of @var{string}. (The shell uses the
71 @code{FNM_PERIOD} and @code{FNM_FILE_NAME} flags together for matching
77 Don't treat the @samp{\} character specially in patterns. Normally,
78 @samp{\} quotes the following character, turning off its special meaning
79 (if any) so that it matches only itself. When quoting is enabled, the
80 pattern @samp{\?} matches only the string @samp{?}, because the question
81 mark in the pattern acts like an ordinary character.
83 If you use @code{FNM_NOESCAPE}, then @samp{\} is an ordinary character.
88 Ignore a trailing sequence of characters starting with a @samp{/} in
89 @var{string}; that is to say, test whether @var{string} starts with a
90 directory name that @var{pattern} matches.
92 If this flag is set, either @samp{foo*} or @samp{foobar} as a pattern
93 would match the string @samp{foobar/frobozz}.
98 Ignore case in comparing @var{string} to @var{pattern}.
105 Recognize beside the normal patterns also the extended patterns
106 introduced in @file{ksh}. The patterns are written in the form
107 explained in the following table where @var{pattern-list} is a @code{|}
108 separated list of patterns.
111 @item ?(@var{pattern-list})
112 The pattern matches if zero or one occurrences of any of the patterns
113 in the @var{pattern-list} allow matching the input string.
115 @item *(@var{pattern-list})
116 The pattern matches if zero or more occurrences of any of the patterns
117 in the @var{pattern-list} allow matching the input string.
119 @item +(@var{pattern-list})
120 The pattern matches if one or more occurrences of any of the patterns
121 in the @var{pattern-list} allow matching the input string.
123 @item @@(@var{pattern-list})
124 The pattern matches if exactly one occurrence of any of the patterns in
125 the @var{pattern-list} allows matching the input string.
127 @item !(@var{pattern-list})
128 The pattern matches if the input string cannot be matched with any of
129 the patterns in the @var{pattern-list}.
137 The archetypal use of wildcards is for matching against the files in a
138 directory, and making a list of all the matches. This is called
141 You could do this using @code{fnmatch}, by reading the directory entries
142 one by one and testing each one with @code{fnmatch}. But that would be
143 slow (and complex, since you would have to handle subdirectories by
146 The library provides a function @code{glob} to make this particular use
147 of wildcards convenient. @code{glob} and the other symbols in this
148 section are declared in @file{glob.h}.
151 * Calling Glob:: Basic use of @code{glob}.
152 * Flags for Globbing:: Flags that enable various options in @code{glob}.
153 * More Flags for Globbing:: GNU specific extensions to @code{glob}.
157 @subsection Calling @code{glob}
159 The result of globbing is a vector of file names (strings). To return
160 this vector, @code{glob} uses a special data type, @code{glob_t}, which
161 is a structure. You pass @code{glob} the address of the structure, and
162 it fills in the structure's fields to tell you about the results.
166 @deftp {Data Type} glob_t
167 This data type holds a pointer to a word vector. More precisely, it
168 records both the address of the word vector and its size. The GNU
169 implementation contains some more fields which are non-standard
174 The number of elements in the vector, excluding the initial null entries
175 if the GLOB_DOOFFS flag is used (see gl_offs below).
178 The address of the vector. This field has type @w{@code{char **}}.
181 The offset of the first real element of the vector, from its nominal
182 address in the @code{gl_pathv} field. Unlike the other fields, this
183 is always an input to @code{glob}, rather than an output from it.
185 If you use a nonzero offset, then that many elements at the beginning of
186 the vector are left empty. (The @code{glob} function fills them with
189 The @code{gl_offs} field is meaningful only if you use the
190 @code{GLOB_DOOFFS} flag. Otherwise, the offset is always zero
191 regardless of what is in this field, and the first real element comes at
192 the beginning of the vector.
195 The address of an alternative implementation of the @code{closedir}
196 function. It is used if the @code{GLOB_ALTDIRFUNC} bit is set in
197 the flag parameter. The type of this field is
198 @w{@code{void (*) (void *)}}.
200 This is a GNU extension.
203 The address of an alternative implementation of the @code{readdir}
204 function used to read the contents of a directory. It is used if the
205 @code{GLOB_ALTDIRFUNC} bit is set in the flag parameter. The type of
206 this field is @w{@code{struct dirent *(*) (void *)}}.
208 This is a GNU extension.
211 The address of an alternative implementation of the @code{opendir}
212 function. It is used if the @code{GLOB_ALTDIRFUNC} bit is set in
213 the flag parameter. The type of this field is
214 @w{@code{void *(*) (const char *)}}.
216 This is a GNU extension.
219 The address of an alternative implementation of the @code{stat} function
220 to get information about an object in the filesystem. It is used if the
221 @code{GLOB_ALTDIRFUNC} bit is set in the flag parameter. The type of
222 this field is @w{@code{int (*) (const char *, struct stat *)}}.
224 This is a GNU extension.
227 The address of an alternative implementation of the @code{lstat}
228 function to get information about an object in the filesystems, not
229 following symbolic links. It is used if the @code{GLOB_ALTDIRFUNC} bit
230 is set in the flag parameter. The type of this field is @code{@w{int
231 (*) (const char *,} @w{struct stat *)}}.
233 This is a GNU extension.
236 The flags used when @code{glob} was called. In addition, @code{GLOB_MAGCHAR}
237 might be set. See @ref{Flags for Globbing} for more details.
239 This is a GNU extension.
243 For use in the @code{glob64} function @file{glob.h} contains another
244 definition for a very similar type. @code{glob64_t} differs from
245 @code{glob_t} only in the types of the members @code{gl_readdir},
246 @code{gl_stat}, and @code{gl_lstat}.
250 @deftp {Data Type} glob64_t
251 This data type holds a pointer to a word vector. More precisely, it
252 records both the address of the word vector and its size. The GNU
253 implementation contains some more fields which are non-standard
258 The number of elements in the vector, excluding the initial null entries
259 if the GLOB_DOOFFS flag is used (see gl_offs below).
262 The address of the vector. This field has type @w{@code{char **}}.
265 The offset of the first real element of the vector, from its nominal
266 address in the @code{gl_pathv} field. Unlike the other fields, this
267 is always an input to @code{glob}, rather than an output from it.
269 If you use a nonzero offset, then that many elements at the beginning of
270 the vector are left empty. (The @code{glob} function fills them with
273 The @code{gl_offs} field is meaningful only if you use the
274 @code{GLOB_DOOFFS} flag. Otherwise, the offset is always zero
275 regardless of what is in this field, and the first real element comes at
276 the beginning of the vector.
279 The address of an alternative implementation of the @code{closedir}
280 function. It is used if the @code{GLOB_ALTDIRFUNC} bit is set in
281 the flag parameter. The type of this field is
282 @w{@code{void (*) (void *)}}.
284 This is a GNU extension.
287 The address of an alternative implementation of the @code{readdir64}
288 function used to read the contents of a directory. It is used if the
289 @code{GLOB_ALTDIRFUNC} bit is set in the flag parameter. The type of
290 this field is @w{@code{struct dirent64 *(*) (void *)}}.
292 This is a GNU extension.
295 The address of an alternative implementation of the @code{opendir}
296 function. It is used if the @code{GLOB_ALTDIRFUNC} bit is set in
297 the flag parameter. The type of this field is
298 @w{@code{void *(*) (const char *)}}.
300 This is a GNU extension.
303 The address of an alternative implementation of the @code{stat64} function
304 to get information about an object in the filesystem. It is used if the
305 @code{GLOB_ALTDIRFUNC} bit is set in the flag parameter. The type of
306 this field is @w{@code{int (*) (const char *, struct stat64 *)}}.
308 This is a GNU extension.
311 The address of an alternative implementation of the @code{lstat64}
312 function to get information about an object in the filesystems, not
313 following symbolic links. It is used if the @code{GLOB_ALTDIRFUNC} bit
314 is set in the flag parameter. The type of this field is @code{@w{int
315 (*) (const char *,} @w{struct stat64 *)}}.
317 This is a GNU extension.
320 The flags used when @code{glob} was called. In addition, @code{GLOB_MAGCHAR}
321 might be set. See @ref{Flags for Globbing} for more details.
323 This is a GNU extension.
329 @deftypefun int glob (const char *@var{pattern}, int @var{flags}, int (*@var{errfunc}) (const char *@var{filename}, int @var{error-code}), glob_t *@var{vector-ptr})
330 The function @code{glob} does globbing using the pattern @var{pattern}
331 in the current directory. It puts the result in a newly allocated
332 vector, and stores the size and address of this vector into
333 @code{*@var{vector-ptr}}. The argument @var{flags} is a combination of
334 bit flags; see @ref{Flags for Globbing}, for details of the flags.
336 The result of globbing is a sequence of file names. The function
337 @code{glob} allocates a string for each resulting word, then
338 allocates a vector of type @code{char **} to store the addresses of
339 these strings. The last element of the vector is a null pointer.
340 This vector is called the @dfn{word vector}.
342 To return this vector, @code{glob} stores both its address and its
343 length (number of elements, not counting the terminating null pointer)
344 into @code{*@var{vector-ptr}}.
346 Normally, @code{glob} sorts the file names alphabetically before
347 returning them. You can turn this off with the flag @code{GLOB_NOSORT}
348 if you want to get the information as fast as possible. Usually it's
349 a good idea to let @code{glob} sort them---if you process the files in
350 alphabetical order, the users will have a feel for the rate of progress
351 that your application is making.
353 If @code{glob} succeeds, it returns 0. Otherwise, it returns one
354 of these error codes:
360 There was an error opening a directory, and you used the flag
361 @code{GLOB_ERR} or your specified @var{errfunc} returned a nonzero
367 @xref{Flags for Globbing},
369 for an explanation of the @code{GLOB_ERR} flag and @var{errfunc}.
374 The pattern didn't match any existing files. If you use the
375 @code{GLOB_NOCHECK} flag, then you never get this error code, because
376 that flag tells @code{glob} to @emph{pretend} that the pattern matched
382 It was impossible to allocate memory to hold the result.
385 In the event of an error, @code{glob} stores information in
386 @code{*@var{vector-ptr}} about all the matches it has found so far.
388 It is important to notice that the @code{glob} function will not fail if
389 it encounters directories or files which cannot be handled without the
390 LFS interfaces. The implementation of @code{glob} is supposed to use
391 these functions internally. This at least is the assumptions made by
392 the Unix standard. The GNU extension of allowing the user to provide
393 own directory handling and @code{stat} functions complicates things a
394 bit. If these callback functions are used and a large file or directory
395 is encountered @code{glob} @emph{can} fail.
400 @deftypefun int glob64 (const char *@var{pattern}, int @var{flags}, int (*@var{errfunc}) (const char *@var{filename}, int @var{error-code}), glob64_t *@var{vector-ptr})
401 The @code{glob64} function was added as part of the Large File Summit
402 extensions but is not part of the original LFS proposal. The reason for
403 this is simple: it is not necessary. The necessity for a @code{glob64}
404 function is added by the extensions of the GNU @code{glob}
405 implementation which allows the user to provide own directory handling
406 and @code{stat} functions. The @code{readdir} and @code{stat} functions
407 do depend on the choice of @code{_FILE_OFFSET_BITS} since the definition
408 of the types @code{struct dirent} and @code{struct stat} will change
409 depending on the choice.
411 Beside this difference the @code{glob64} works just like @code{glob} in
414 This function is a GNU extension.
417 @node Flags for Globbing
418 @subsection Flags for Globbing
420 This section describes the standard flags that you can specify in the
421 @var{flags} argument to @code{glob}. Choose the flags you want,
422 and combine them with the C bitwise OR operator @code{|}.
424 Note that there are @ref{More Flags for Globbing} available as GNU extensions.
430 Append the words from this expansion to the vector of words produced by
431 previous calls to @code{glob}. This way you can effectively expand
432 several words as if they were concatenated with spaces between them.
434 In order for appending to work, you must not modify the contents of the
435 word vector structure between calls to @code{glob}. And, if you set
436 @code{GLOB_DOOFFS} in the first call to @code{glob}, you must also
437 set it when you append to the results.
439 Note that the pointer stored in @code{gl_pathv} may no longer be valid
440 after you call @code{glob} the second time, because @code{glob} might
441 have relocated the vector. So always fetch @code{gl_pathv} from the
442 @code{glob_t} structure after each @code{glob} call; @strong{never} save
443 the pointer across calls.
448 Leave blank slots at the beginning of the vector of words.
449 The @code{gl_offs} field says how many slots to leave.
450 The blank slots contain null pointers.
455 Give up right away and report an error if there is any difficulty
456 reading the directories that must be read in order to expand @var{pattern}
457 fully. Such difficulties might include a directory in which you don't
458 have the requisite access. Normally, @code{glob} tries its best to keep
459 on going despite any errors, reading whatever directories it can.
461 You can exercise even more control than this by specifying an
462 error-handler function @var{errfunc} when you call @code{glob}. If
463 @var{errfunc} is not a null pointer, then @code{glob} doesn't give up
464 right away when it can't read a directory; instead, it calls
465 @var{errfunc} with two arguments, like this:
468 (*@var{errfunc}) (@var{filename}, @var{error-code})
472 The argument @var{filename} is the name of the directory that
473 @code{glob} couldn't open or couldn't read, and @var{error-code} is the
474 @code{errno} value that was reported to @code{glob}.
476 If the error handler function returns nonzero, then @code{glob} gives up
477 right away. Otherwise, it continues.
482 If the pattern matches the name of a directory, append @samp{/} to the
483 directory's name when returning it.
488 If the pattern doesn't match any file names, return the pattern itself
489 as if it were a file name that had been matched. (Normally, when the
490 pattern doesn't match anything, @code{glob} returns that there were no
496 Don't treat the @samp{\} character specially in patterns. Normally,
497 @samp{\} quotes the following character, turning off its special meaning
498 (if any) so that it matches only itself. When quoting is enabled, the
499 pattern @samp{\?} matches only the string @samp{?}, because the question
500 mark in the pattern acts like an ordinary character.
502 If you use @code{GLOB_NOESCAPE}, then @samp{\} is an ordinary character.
504 @code{glob} does its work by calling the function @code{fnmatch}
505 repeatedly. It handles the flag @code{GLOB_NOESCAPE} by turning on the
506 @code{FNM_NOESCAPE} flag in calls to @code{fnmatch}.
511 Don't sort the file names; return them in no particular order.
512 (In practice, the order will depend on the order of the entries in
513 the directory.) The only reason @emph{not} to sort is to save time.
516 @node More Flags for Globbing
517 @subsection More Flags for Globbing
519 Beside the flags described in the last section, the GNU implementation of
520 @code{glob} allows a few more flags which are also defined in the
521 @file{glob.h} file. Some of the extensions implement functionality
522 which is available in modern shell implementations.
528 The @code{.} character (period) is treated special. It cannot be
529 matched by wildcards. @xref{Wildcard Matching}, @code{FNM_PERIOD}.
534 The @code{GLOB_MAGCHAR} value is not to be given to @code{glob} in the
535 @var{flags} parameter. Instead, @code{glob} sets this bit in the
536 @var{gl_flags} element of the @var{glob_t} structure provided as the
537 result if the pattern used for matching contains any wildcard character.
541 @item GLOB_ALTDIRFUNC
542 Instead of the using the using the normal functions for accessing the
543 filesystem the @code{glob} implementation uses the user-supplied
544 functions specified in the structure pointed to by @var{pglob}
545 parameter. For more information about the functions refer to the
546 sections about directory handling see @ref{Accessing Directories}, and
547 @ref{Reading Attributes}.
552 If this flag is given the handling of braces in the pattern is changed.
553 It is now required that braces appear correctly grouped. I.e., for each
554 opening brace there must be a closing one. Braces can be used
555 recursively. So it is possible to define one brace expression in
556 another one. It is important to note that the range of each brace
557 expression is completely contained in the outer brace expression (if
560 The string between the matching braces is separated into single
561 expressions by splitting at @code{,} (comma) characters. The commas
562 themselves are discarded. Please note what we said above about recursive
563 brace expressions. The commas used to separate the subexpressions must
564 be at the same level. Commas in brace subexpressions are not matched.
565 They are used during expansion of the brace expression of the deeper
566 level. The example below shows this
569 glob ("@{foo/@{,bar,biz@},baz@}", GLOB_BRACE, NULL, &result)
573 is equivalent to the sequence
576 glob ("foo/", GLOB_BRACE, NULL, &result)
577 glob ("foo/bar", GLOB_BRACE|GLOB_APPEND, NULL, &result)
578 glob ("foo/biz", GLOB_BRACE|GLOB_APPEND, NULL, &result)
579 glob ("baz", GLOB_BRACE|GLOB_APPEND, NULL, &result)
583 if we leave aside error handling.
588 If the pattern contains no wildcard constructs (it is a literal file name),
589 return it as the sole ``matching'' word, even if no file exists by that name.
594 If this flag is used the character @code{~} (tilde) is handled special
595 if it appears at the beginning of the pattern. Instead of being taken
596 verbatim it is used to represent the home directory of a known user.
598 If @code{~} is the only character in pattern or it is followed by a
599 @code{/} (slash), the home directory of the process owner is
600 substituted. Using @code{getlogin} and @code{getpwnam} the information
601 is read from the system databases. As an example take user @code{bart}
602 with his home directory at @file{/home/bart}. For him a call like
605 glob ("~/bin/*", GLOB_TILDE, NULL, &result)
609 would return the contents of the directory @file{/home/bart/bin}.
610 Instead of referring to the own home directory it is also possible to
611 name the home directory of other users. To do so one has to append the
612 user name after the tilde character. So the contents of user
613 @code{homer}'s @file{bin} directory can be retrieved by
616 glob ("~homer/bin/*", GLOB_TILDE, NULL, &result)
619 If the user name is not valid or the home directory cannot be determined
620 for some reason the pattern is left untouched and itself used as the
621 result. I.e., if in the last example @code{home} is not available the
622 tilde expansion yields to @code{"~homer/bin/*"} and @code{glob} is not
623 looking for a directory named @code{~homer}.
625 This functionality is equivalent to what is available in C-shells if the
626 @code{nonomatch} flag is set.
630 @item GLOB_TILDE_CHECK
631 If this flag is used @code{glob} behaves like as if @code{GLOB_TILDE} is
632 given. The only difference is that if the user name is not available or
633 the home directory cannot be determined for other reasons this leads to
634 an error. @code{glob} will return @code{GLOB_NOMATCH} instead of using
635 the pattern itself as the name.
637 This functionality is equivalent to what is available in C-shells if
638 @code{nonomatch} flag is not set.
643 If this flag is used the globbing function takes this as a
644 @strong{hint} that the caller is only interested in directories
645 matching the pattern. If the information about the type of the file
646 is easily available non-directories will be rejected but no extra
647 work will be done to determine the information for each file. I.e.,
648 the caller must still be able to filter directories out.
650 This functionality is only available with the GNU @code{glob}
651 implementation. It is mainly used internally to increase the
652 performance but might be useful for a user as well and therefore is
656 Calling @code{glob} will in most cases allocate resources which are used
657 to represent the result of the function call. If the same object of
658 type @code{glob_t} is used in multiple call to @code{glob} the resources
659 are freed or reused so that no leaks appear. But this does not include
660 the time when all @code{glob} calls are done.
664 @deftypefun void globfree (glob_t *@var{pglob})
665 The @code{globfree} function frees all resources allocated by previous
666 calls to @code{glob} associated with the object pointed to by
667 @var{pglob}. This function should be called whenever the currently used
668 @code{glob_t} typed object isn't used anymore.
673 @deftypefun void globfree64 (glob64_t *@var{pglob})
674 This function is equivalent to @code{globfree} but it frees records of
675 type @code{glob64_t} which were allocated by @code{glob64}.
679 @node Regular Expressions
680 @section Regular Expression Matching
682 @Theglibc{} supports two interfaces for matching regular
683 expressions. One is the standard POSIX.2 interface, and the other is
684 what @theglibc{} has had for many years.
686 Both interfaces are declared in the header file @file{regex.h}.
687 If you define @w{@code{_POSIX_C_SOURCE}}, then only the POSIX.2
688 functions, structures, and constants are declared.
689 @c !!! we only document the POSIX.2 interface here!!
692 * POSIX Regexp Compilation:: Using @code{regcomp} to prepare to match.
693 * Flags for POSIX Regexps:: Syntax variations for @code{regcomp}.
694 * Matching POSIX Regexps:: Using @code{regexec} to match the compiled
695 pattern that you get from @code{regcomp}.
696 * Regexp Subexpressions:: Finding which parts of the string were matched.
697 * Subexpression Complications:: Find points of which parts were matched.
698 * Regexp Cleanup:: Freeing storage; reporting errors.
701 @node POSIX Regexp Compilation
702 @subsection POSIX Regular Expression Compilation
704 Before you can actually match a regular expression, you must
705 @dfn{compile} it. This is not true compilation---it produces a special
706 data structure, not machine instructions. But it is like ordinary
707 compilation in that its purpose is to enable you to ``execute'' the
708 pattern fast. (@xref{Matching POSIX Regexps}, for how to use the
709 compiled regular expression for matching.)
711 There is a special data type for compiled regular expressions:
715 @deftp {Data Type} regex_t
716 This type of object holds a compiled regular expression.
717 It is actually a structure. It has just one field that your programs
722 This field holds the number of parenthetical subexpressions in the
723 regular expression that was compiled.
726 There are several other fields, but we don't describe them here, because
727 only the functions in the library should use them.
730 After you create a @code{regex_t} object, you can compile a regular
731 expression into it by calling @code{regcomp}.
735 @deftypefun int regcomp (regex_t *restrict @var{compiled}, const char *restrict @var{pattern}, int @var{cflags})
736 The function @code{regcomp} ``compiles'' a regular expression into a
737 data structure that you can use with @code{regexec} to match against a
738 string. The compiled regular expression format is designed for
739 efficient matching. @code{regcomp} stores it into @code{*@var{compiled}}.
741 It's up to you to allocate an object of type @code{regex_t} and pass its
742 address to @code{regcomp}.
744 The argument @var{cflags} lets you specify various options that control
745 the syntax and semantics of regular expressions. @xref{Flags for POSIX
748 If you use the flag @code{REG_NOSUB}, then @code{regcomp} omits from
749 the compiled regular expression the information necessary to record
750 how subexpressions actually match. In this case, you might as well
751 pass @code{0} for the @var{matchptr} and @var{nmatch} arguments when
752 you call @code{regexec}.
754 If you don't use @code{REG_NOSUB}, then the compiled regular expression
755 does have the capacity to record how subexpressions match. Also,
756 @code{regcomp} tells you how many subexpressions @var{pattern} has, by
757 storing the number in @code{@var{compiled}->re_nsub}. You can use that
758 value to decide how long an array to allocate to hold information about
759 subexpression matches.
761 @code{regcomp} returns @code{0} if it succeeds in compiling the regular
762 expression; otherwise, it returns a nonzero error code (see the table
763 below). You can use @code{regerror} to produce an error message string
764 describing the reason for a nonzero value; see @ref{Regexp Cleanup}.
768 Here are the possible nonzero values that @code{regcomp} can return:
774 There was an invalid @samp{\@{@dots{}\@}} construct in the regular
775 expression. A valid @samp{\@{@dots{}\@}} construct must contain either
776 a single number, or two numbers in increasing order separated by a
782 There was a syntax error in the regular expression.
787 A repetition operator such as @samp{?} or @samp{*} appeared in a bad
788 position (with no preceding subexpression to act on).
793 The regular expression referred to an invalid collating element (one not
794 defined in the current locale for string collation). @xref{Locale
800 The regular expression referred to an invalid character class name.
805 The regular expression ended with @samp{\}.
810 There was an invalid number in the @samp{\@var{digit}} construct.
815 There were unbalanced square brackets in the regular expression.
820 An extended regular expression had unbalanced parentheses,
821 or a basic regular expression had unbalanced @samp{\(} and @samp{\)}.
826 The regular expression had unbalanced @samp{\@{} and @samp{\@}}.
831 One of the endpoints in a range expression was invalid.
836 @code{regcomp} ran out of memory.
839 @node Flags for POSIX Regexps
840 @subsection Flags for POSIX Regular Expressions
842 These are the bit flags that you can use in the @var{cflags} operand when
843 compiling a regular expression with @code{regcomp}.
849 Treat the pattern as an extended regular expression, rather than as a
850 basic regular expression.
855 Ignore case when matching letters.
860 Don't bother storing the contents of the @var{matches-ptr} array.
865 Treat a newline in @var{string} as dividing @var{string} into multiple
866 lines, so that @samp{$} can match before the newline and @samp{^} can
867 match after. Also, don't permit @samp{.} to match a newline, and don't
868 permit @samp{[^@dots{}]} to match a newline.
870 Otherwise, newline acts like any other ordinary character.
873 @node Matching POSIX Regexps
874 @subsection Matching a Compiled POSIX Regular Expression
876 Once you have compiled a regular expression, as described in @ref{POSIX
877 Regexp Compilation}, you can match it against strings using
878 @code{regexec}. A match anywhere inside the string counts as success,
879 unless the regular expression contains anchor characters (@samp{^} or
884 @deftypefun int regexec (const regex_t *restrict @var{compiled}, const char *restrict @var{string}, size_t @var{nmatch}, regmatch_t @var{matchptr}[restrict], int @var{eflags})
885 This function tries to match the compiled regular expression
886 @code{*@var{compiled}} against @var{string}.
888 @code{regexec} returns @code{0} if the regular expression matches;
889 otherwise, it returns a nonzero value. See the table below for
890 what nonzero values mean. You can use @code{regerror} to produce an
891 error message string describing the reason for a nonzero value;
892 see @ref{Regexp Cleanup}.
894 The argument @var{eflags} is a word of bit flags that enable various
897 If you want to get information about what part of @var{string} actually
898 matched the regular expression or its subexpressions, use the arguments
899 @var{matchptr} and @var{nmatch}. Otherwise, pass @code{0} for
900 @var{nmatch}, and @code{NULL} for @var{matchptr}. @xref{Regexp
904 You must match the regular expression with the same set of current
905 locales that were in effect when you compiled the regular expression.
907 The function @code{regexec} accepts the following flags in the
908 @var{eflags} argument:
914 Do not regard the beginning of the specified string as the beginning of
915 a line; more generally, don't make any assumptions about what text might
921 Do not regard the end of the specified string as the end of a line; more
922 generally, don't make any assumptions about what text might follow it.
925 Here are the possible nonzero values that @code{regexec} can return:
931 The pattern didn't match the string. This isn't really an error.
936 @code{regexec} ran out of memory.
939 @node Regexp Subexpressions
940 @subsection Match Results with Subexpressions
942 When @code{regexec} matches parenthetical subexpressions of
943 @var{pattern}, it records which parts of @var{string} they match. It
944 returns that information by storing the offsets into an array whose
945 elements are structures of type @code{regmatch_t}. The first element of
946 the array (index @code{0}) records the part of the string that matched
947 the entire regular expression. Each other element of the array records
948 the beginning and end of the part that matched a single parenthetical
953 @deftp {Data Type} regmatch_t
954 This is the data type of the @var{matcharray} array that you pass to
955 @code{regexec}. It contains two structure fields, as follows:
959 The offset in @var{string} of the beginning of a substring. Add this
960 value to @var{string} to get the address of that part.
963 The offset in @var{string} of the end of the substring.
969 @deftp {Data Type} regoff_t
970 @code{regoff_t} is an alias for another signed integer type.
971 The fields of @code{regmatch_t} have type @code{regoff_t}.
974 The @code{regmatch_t} elements correspond to subexpressions
975 positionally; the first element (index @code{1}) records where the first
976 subexpression matched, the second element records the second
977 subexpression, and so on. The order of the subexpressions is the order
980 When you call @code{regexec}, you specify how long the @var{matchptr}
981 array is, with the @var{nmatch} argument. This tells @code{regexec} how
982 many elements to store. If the actual regular expression has more than
983 @var{nmatch} subexpressions, then you won't get offset information about
984 the rest of them. But this doesn't alter whether the pattern matches a
985 particular string or not.
987 If you don't want @code{regexec} to return any information about where
988 the subexpressions matched, you can either supply @code{0} for
989 @var{nmatch}, or use the flag @code{REG_NOSUB} when you compile the
990 pattern with @code{regcomp}.
992 @node Subexpression Complications
993 @subsection Complications in Subexpression Matching
995 Sometimes a subexpression matches a substring of no characters. This
996 happens when @samp{f\(o*\)} matches the string @samp{fum}. (It really
997 matches just the @samp{f}.) In this case, both of the offsets identify
998 the point in the string where the null substring was found. In this
999 example, the offsets are both @code{1}.
1001 Sometimes the entire regular expression can match without using some of
1002 its subexpressions at all---for example, when @samp{ba\(na\)*} matches the
1003 string @samp{ba}, the parenthetical subexpression is not used. When
1004 this happens, @code{regexec} stores @code{-1} in both fields of the
1005 element for that subexpression.
1007 Sometimes matching the entire regular expression can match a particular
1008 subexpression more than once---for example, when @samp{ba\(na\)*}
1009 matches the string @samp{bananana}, the parenthetical subexpression
1010 matches three times. When this happens, @code{regexec} usually stores
1011 the offsets of the last part of the string that matched the
1012 subexpression. In the case of @samp{bananana}, these offsets are
1013 @code{6} and @code{8}.
1015 But the last match is not always the one that is chosen. It's more
1016 accurate to say that the last @emph{opportunity} to match is the one
1017 that takes precedence. What this means is that when one subexpression
1018 appears within another, then the results reported for the inner
1019 subexpression reflect whatever happened on the last match of the outer
1020 subexpression. For an example, consider @samp{\(ba\(na\)*s \)*} matching
1021 the string @samp{bananas bas }. The last time the inner expression
1022 actually matches is near the end of the first word. But it is
1023 @emph{considered} again in the second word, and fails to match there.
1024 @code{regexec} reports nonuse of the ``na'' subexpression.
1026 Another place where this rule applies is when the regular expression
1028 \(ba\(na\)*s \|nefer\(ti\)* \)*
1031 matches @samp{bananas nefertiti}. The ``na'' subexpression does match
1032 in the first word, but it doesn't match in the second word because the
1033 other alternative is used there. Once again, the second repetition of
1034 the outer subexpression overrides the first, and within that second
1035 repetition, the ``na'' subexpression is not used. So @code{regexec}
1036 reports nonuse of the ``na'' subexpression.
1038 @node Regexp Cleanup
1039 @subsection POSIX Regexp Matching Cleanup
1041 When you are finished using a compiled regular expression, you can
1042 free the storage it uses by calling @code{regfree}.
1046 @deftypefun void regfree (regex_t *@var{compiled})
1047 Calling @code{regfree} frees all the storage that @code{*@var{compiled}}
1048 points to. This includes various internal fields of the @code{regex_t}
1049 structure that aren't documented in this manual.
1051 @code{regfree} does not free the object @code{*@var{compiled}} itself.
1054 You should always free the space in a @code{regex_t} structure with
1055 @code{regfree} before using the structure to compile another regular
1058 When @code{regcomp} or @code{regexec} reports an error, you can use
1059 the function @code{regerror} to turn it into an error message string.
1063 @deftypefun size_t regerror (int @var{errcode}, const regex_t *restrict @var{compiled}, char *restrict @var{buffer}, size_t @var{length})
1064 This function produces an error message string for the error code
1065 @var{errcode}, and stores the string in @var{length} bytes of memory
1066 starting at @var{buffer}. For the @var{compiled} argument, supply the
1067 same compiled regular expression structure that @code{regcomp} or
1068 @code{regexec} was working with when it got the error. Alternatively,
1069 you can supply @code{NULL} for @var{compiled}; you will still get a
1070 meaningful error message, but it might not be as detailed.
1072 If the error message can't fit in @var{length} bytes (including a
1073 terminating null character), then @code{regerror} truncates it.
1074 The string that @code{regerror} stores is always null-terminated
1075 even if it has been truncated.
1077 The return value of @code{regerror} is the minimum length needed to
1078 store the entire error message. If this is less than @var{length}, then
1079 the error message was not truncated, and you can use it. Otherwise, you
1080 should call @code{regerror} again with a larger buffer.
1082 Here is a function which uses @code{regerror}, but always dynamically
1083 allocates a buffer for the error message:
1086 char *get_regerror (int errcode, regex_t *compiled)
1088 size_t length = regerror (errcode, compiled, NULL, 0);
1089 char *buffer = xmalloc (length);
1090 (void) regerror (errcode, compiled, buffer, length);
1096 @node Word Expansion
1097 @section Shell-Style Word Expansion
1098 @cindex word expansion
1099 @cindex expansion of shell words
1101 @dfn{Word expansion} means the process of splitting a string into
1102 @dfn{words} and substituting for variables, commands, and wildcards
1103 just as the shell does.
1105 For example, when you write @samp{ls -l foo.c}, this string is split
1106 into three separate words---@samp{ls}, @samp{-l} and @samp{foo.c}.
1107 This is the most basic function of word expansion.
1109 When you write @samp{ls *.c}, this can become many words, because
1110 the word @samp{*.c} can be replaced with any number of file names.
1111 This is called @dfn{wildcard expansion}, and it is also a part of
1114 When you use @samp{echo $PATH} to print your path, you are taking
1115 advantage of @dfn{variable substitution}, which is also part of word
1118 Ordinary programs can perform word expansion just like the shell by
1119 calling the library function @code{wordexp}.
1122 * Expansion Stages:: What word expansion does to a string.
1123 * Calling Wordexp:: How to call @code{wordexp}.
1124 * Flags for Wordexp:: Options you can enable in @code{wordexp}.
1125 * Wordexp Example:: A sample program that does word expansion.
1126 * Tilde Expansion:: Details of how tilde expansion works.
1127 * Variable Substitution:: Different types of variable substitution.
1130 @node Expansion Stages
1131 @subsection The Stages of Word Expansion
1133 When word expansion is applied to a sequence of words, it performs the
1134 following transformations in the order shown here:
1138 @cindex tilde expansion
1139 @dfn{Tilde expansion}: Replacement of @samp{~foo} with the name of
1140 the home directory of @samp{foo}.
1143 Next, three different transformations are applied in the same step,
1148 @cindex variable substitution
1149 @cindex substitution of variables and commands
1150 @dfn{Variable substitution}: Environment variables are substituted for
1151 references such as @samp{$foo}.
1154 @cindex command substitution
1155 @dfn{Command substitution}: Constructs such as @w{@samp{`cat foo`}} and
1156 the equivalent @w{@samp{$(cat foo)}} are replaced with the output from
1160 @cindex arithmetic expansion
1161 @dfn{Arithmetic expansion}: Constructs such as @samp{$(($x-1))} are
1162 replaced with the result of the arithmetic computation.
1166 @cindex field splitting
1167 @dfn{Field splitting}: subdivision of the text into @dfn{words}.
1170 @cindex wildcard expansion
1171 @dfn{Wildcard expansion}: The replacement of a construct such as @samp{*.c}
1172 with a list of @samp{.c} file names. Wildcard expansion applies to an
1173 entire word at a time, and replaces that word with 0 or more file names
1174 that are themselves words.
1177 @cindex quote removal
1178 @cindex removal of quotes
1179 @dfn{Quote removal}: The deletion of string-quotes, now that they have
1180 done their job by inhibiting the above transformations when appropriate.
1183 For the details of these transformations, and how to write the constructs
1184 that use them, see @w{@cite{The BASH Manual}} (to appear).
1186 @node Calling Wordexp
1187 @subsection Calling @code{wordexp}
1189 All the functions, constants and data types for word expansion are
1190 declared in the header file @file{wordexp.h}.
1192 Word expansion produces a vector of words (strings). To return this
1193 vector, @code{wordexp} uses a special data type, @code{wordexp_t}, which
1194 is a structure. You pass @code{wordexp} the address of the structure,
1195 and it fills in the structure's fields to tell you about the results.
1199 @deftp {Data Type} {wordexp_t}
1200 This data type holds a pointer to a word vector. More precisely, it
1201 records both the address of the word vector and its size.
1205 The number of elements in the vector.
1208 The address of the vector. This field has type @w{@code{char **}}.
1211 The offset of the first real element of the vector, from its nominal
1212 address in the @code{we_wordv} field. Unlike the other fields, this
1213 is always an input to @code{wordexp}, rather than an output from it.
1215 If you use a nonzero offset, then that many elements at the beginning of
1216 the vector are left empty. (The @code{wordexp} function fills them with
1219 The @code{we_offs} field is meaningful only if you use the
1220 @code{WRDE_DOOFFS} flag. Otherwise, the offset is always zero
1221 regardless of what is in this field, and the first real element comes at
1222 the beginning of the vector.
1228 @deftypefun int wordexp (const char *@var{words}, wordexp_t *@var{word-vector-ptr}, int @var{flags})
1229 Perform word expansion on the string @var{words}, putting the result in
1230 a newly allocated vector, and store the size and address of this vector
1231 into @code{*@var{word-vector-ptr}}. The argument @var{flags} is a
1232 combination of bit flags; see @ref{Flags for Wordexp}, for details of
1235 You shouldn't use any of the characters @samp{|&;<>} in the string
1236 @var{words} unless they are quoted; likewise for newline. If you use
1237 these characters unquoted, you will get the @code{WRDE_BADCHAR} error
1238 code. Don't use parentheses or braces unless they are quoted or part of
1239 a word expansion construct. If you use quotation characters @samp{'"`},
1240 they should come in pairs that balance.
1242 The results of word expansion are a sequence of words. The function
1243 @code{wordexp} allocates a string for each resulting word, then
1244 allocates a vector of type @code{char **} to store the addresses of
1245 these strings. The last element of the vector is a null pointer.
1246 This vector is called the @dfn{word vector}.
1248 To return this vector, @code{wordexp} stores both its address and its
1249 length (number of elements, not counting the terminating null pointer)
1250 into @code{*@var{word-vector-ptr}}.
1252 If @code{wordexp} succeeds, it returns 0. Otherwise, it returns one
1253 of these error codes:
1259 The input string @var{words} contains an unquoted invalid character such
1265 The input string refers to an undefined shell variable, and you used the flag
1266 @code{WRDE_UNDEF} to forbid such references.
1271 The input string uses command substitution, and you used the flag
1272 @code{WRDE_NOCMD} to forbid command substitution.
1277 It was impossible to allocate memory to hold the result. In this case,
1278 @code{wordexp} can store part of the results---as much as it could
1284 There was a syntax error in the input string. For example, an unmatched
1285 quoting character is a syntax error.
1291 @deftypefun void wordfree (wordexp_t *@var{word-vector-ptr})
1292 Free the storage used for the word-strings and vector that
1293 @code{*@var{word-vector-ptr}} points to. This does not free the
1294 structure @code{*@var{word-vector-ptr}} itself---only the other
1298 @node Flags for Wordexp
1299 @subsection Flags for Word Expansion
1301 This section describes the flags that you can specify in the
1302 @var{flags} argument to @code{wordexp}. Choose the flags you want,
1303 and combine them with the C operator @code{|}.
1309 Append the words from this expansion to the vector of words produced by
1310 previous calls to @code{wordexp}. This way you can effectively expand
1311 several words as if they were concatenated with spaces between them.
1313 In order for appending to work, you must not modify the contents of the
1314 word vector structure between calls to @code{wordexp}. And, if you set
1315 @code{WRDE_DOOFFS} in the first call to @code{wordexp}, you must also
1316 set it when you append to the results.
1321 Leave blank slots at the beginning of the vector of words.
1322 The @code{we_offs} field says how many slots to leave.
1323 The blank slots contain null pointers.
1328 Don't do command substitution; if the input requests command substitution,
1334 Reuse a word vector made by a previous call to @code{wordexp}.
1335 Instead of allocating a new vector of words, this call to @code{wordexp}
1336 will use the vector that already exists (making it larger if necessary).
1338 Note that the vector may move, so it is not safe to save an old pointer
1339 and use it again after calling @code{wordexp}. You must fetch
1340 @code{we_pathv} anew after each call.
1345 Do show any error messages printed by commands run by command substitution.
1346 More precisely, allow these commands to inherit the standard error output
1347 stream of the current process. By default, @code{wordexp} gives these
1348 commands a standard error stream that discards all output.
1353 If the input refers to a shell variable that is not defined, report an
1357 @node Wordexp Example
1358 @subsection @code{wordexp} Example
1360 Here is an example of using @code{wordexp} to expand several strings
1361 and use the results to run a shell command. It also shows the use of
1362 @code{WRDE_APPEND} to concatenate the expansions and of @code{wordfree}
1363 to free the space allocated by @code{wordexp}.
1367 expand_and_execute (const char *program, const char **options)
1373 /* @r{Expand the string for the program to run.} */
1374 switch (wordexp (program, &result, 0))
1376 case 0: /* @r{Successful}. */
1379 /* @r{If the error was @code{WRDE_NOSPACE},}
1380 @r{then perhaps part of the result was allocated.} */
1382 default: /* @r{Some other error.} */
1386 /* @r{Expand the strings specified for the arguments.} */
1387 for (i = 0; options[i] != NULL; i++)
1389 if (wordexp (options[i], &result, WRDE_APPEND))
1399 /* @r{This is the child process. Execute the command.} */
1400 execv (result.we_wordv[0], result.we_wordv);
1401 exit (EXIT_FAILURE);
1404 /* @r{The fork failed. Report failure.} */
1407 /* @r{This is the parent process. Wait for the child to complete.} */
1408 if (waitpid (pid, &status, 0) != pid)
1416 @node Tilde Expansion
1417 @subsection Details of Tilde Expansion
1419 It's a standard part of shell syntax that you can use @samp{~} at the
1420 beginning of a file name to stand for your own home directory. You
1421 can use @samp{~@var{user}} to stand for @var{user}'s home directory.
1423 @dfn{Tilde expansion} is the process of converting these abbreviations
1424 to the directory names that they stand for.
1426 Tilde expansion applies to the @samp{~} plus all following characters up
1427 to whitespace or a slash. It takes place only at the beginning of a
1428 word, and only if none of the characters to be transformed is quoted in
1431 Plain @samp{~} uses the value of the environment variable @code{HOME}
1432 as the proper home directory name. @samp{~} followed by a user name
1433 uses @code{getpwname} to look up that user in the user database, and
1434 uses whatever directory is recorded there. Thus, @samp{~} followed
1435 by your own name can give different results from plain @samp{~}, if
1436 the value of @code{HOME} is not really your home directory.
1438 @node Variable Substitution
1439 @subsection Details of Variable Substitution
1441 Part of ordinary shell syntax is the use of @samp{$@var{variable}} to
1442 substitute the value of a shell variable into a command. This is called
1443 @dfn{variable substitution}, and it is one part of doing word expansion.
1445 There are two basic ways you can write a variable reference for
1449 @item $@{@var{variable}@}
1450 If you write braces around the variable name, then it is completely
1451 unambiguous where the variable name ends. You can concatenate
1452 additional letters onto the end of the variable value by writing them
1453 immediately after the close brace. For example, @samp{$@{foo@}s}
1454 expands into @samp{tractors}.
1456 @item $@var{variable}
1457 If you do not put braces around the variable name, then the variable
1458 name consists of all the alphanumeric characters and underscores that
1459 follow the @samp{$}. The next punctuation character ends the variable
1460 name. Thus, @samp{$foo-bar} refers to the variable @code{foo} and expands
1461 into @samp{tractor-bar}.
1464 When you use braces, you can also use various constructs to modify the
1465 value that is substituted, or test it in various ways.
1468 @item $@{@var{variable}:-@var{default}@}
1469 Substitute the value of @var{variable}, but if that is empty or
1470 undefined, use @var{default} instead.
1472 @item $@{@var{variable}:=@var{default}@}
1473 Substitute the value of @var{variable}, but if that is empty or
1474 undefined, use @var{default} instead and set the variable to
1477 @item $@{@var{variable}:?@var{message}@}
1478 If @var{variable} is defined and not empty, substitute its value.
1480 Otherwise, print @var{message} as an error message on the standard error
1481 stream, and consider word expansion a failure.
1483 @c ??? How does wordexp report such an error?
1484 @c WRDE_BADVAL is returned.
1486 @item $@{@var{variable}:+@var{replacement}@}
1487 Substitute @var{replacement}, but only if @var{variable} is defined and
1488 nonempty. Otherwise, substitute nothing for this construct.
1492 @item $@{#@var{variable}@}
1493 Substitute a numeral which expresses in base ten the number of
1494 characters in the value of @var{variable}. @samp{$@{#foo@}} stands for
1495 @samp{7}, because @samp{tractor} is seven characters.
1498 These variants of variable substitution let you remove part of the
1499 variable's value before substituting it. The @var{prefix} and
1500 @var{suffix} are not mere strings; they are wildcard patterns, just
1501 like the patterns that you use to match multiple file names. But
1502 in this context, they match against parts of the variable value
1503 rather than against file names.
1506 @item $@{@var{variable}%%@var{suffix}@}
1507 Substitute the value of @var{variable}, but first discard from that
1508 variable any portion at the end that matches the pattern @var{suffix}.
1510 If there is more than one alternative for how to match against
1511 @var{suffix}, this construct uses the longest possible match.
1513 Thus, @samp{$@{foo%%r*@}} substitutes @samp{t}, because the largest
1514 match for @samp{r*} at the end of @samp{tractor} is @samp{ractor}.
1516 @item $@{@var{variable}%@var{suffix}@}
1517 Substitute the value of @var{variable}, but first discard from that
1518 variable any portion at the end that matches the pattern @var{suffix}.
1520 If there is more than one alternative for how to match against
1521 @var{suffix}, this construct uses the shortest possible alternative.
1523 Thus, @samp{$@{foo%r*@}} substitutes @samp{tracto}, because the shortest
1524 match for @samp{r*} at the end of @samp{tractor} is just @samp{r}.
1526 @item $@{@var{variable}##@var{prefix}@}
1527 Substitute the value of @var{variable}, but first discard from that
1528 variable any portion at the beginning that matches the pattern @var{prefix}.
1530 If there is more than one alternative for how to match against
1531 @var{prefix}, this construct uses the longest possible match.
1533 Thus, @samp{$@{foo##*t@}} substitutes @samp{or}, because the largest
1534 match for @samp{*t} at the beginning of @samp{tractor} is @samp{tract}.
1536 @item $@{@var{variable}#@var{prefix}@}
1537 Substitute the value of @var{variable}, but first discard from that
1538 variable any portion at the beginning that matches the pattern @var{prefix}.
1540 If there is more than one alternative for how to match against
1541 @var{prefix}, this construct uses the shortest possible alternative.
1543 Thus, @samp{$@{foo#*t@}} substitutes @samp{ractor}, because the shortest
1544 match for @samp{*t} at the beginning of @samp{tractor} is just @samp{t}.