update from main archive 970203
[glibc.git] / manual / pattern.texi
blob6ac481ab6e5fde84d41885cc3fcbd5578ccf926a
1 @node Pattern Matching, I/O Overview, Searching and Sorting, Top
2 @chapter Pattern Matching
4 The GNU C Library provides pattern matching facilities for two kinds of
5 patterns: regular expressions and file-name wildcards.  The library also
6 provides a facility for expanding variable and command references and
7 parsing text into words in the way the shell does.
9 @menu
10 * Wildcard Matching::    Matching a wildcard pattern against a single string.
11 * Globbing::             Finding the files that match a wildcard pattern.
12 * Regular Expressions::  Matching regular expressions against strings.
13 * Word Expansion::       Expanding shell variables, nested commands,
14                             arithmetic, and wildcards.
15                             This is what the shell does with shell commands.
16 @end menu
18 @node Wildcard Matching
19 @section Wildcard Matching
21 @pindex fnmatch.h
22 This section describes how to match a wildcard pattern against a
23 particular string.  The result is a yes or no answer: does the
24 string fit the pattern or not.  The symbols described here are all
25 declared in @file{fnmatch.h}.
27 @comment fnmatch.h
28 @comment POSIX.2
29 @deftypefun int fnmatch (const char *@var{pattern}, const char *@var{string}, int @var{flags})
30 This function tests whether the string @var{string} matches the pattern
31 @var{pattern}.  It returns @code{0} if they do match; otherwise, it
32 returns the nonzero value @code{FNM_NOMATCH}.  The arguments
33 @var{pattern} and @var{string} are both strings.
35 The argument @var{flags} is a combination of flag bits that alter the
36 details of matching.  See below for a list of the defined flags.
38 In the GNU C Library, @code{fnmatch} cannot experience an ``error''---it
39 always returns an answer for whether the match succeeds.  However, other
40 implementations of @code{fnmatch} might sometimes report ``errors''.
41 They would do so by returning nonzero values that are not equal to
42 @code{FNM_NOMATCH}.
43 @end deftypefun
45 These are the available flags for the @var{flags} argument:
47 @table @code
48 @comment fnmatch.h
49 @comment GNU
50 @item FNM_FILE_NAME
51 Treat the @samp{/} character specially, for matching file names.  If
52 this flag is set, wildcard constructs in @var{pattern} cannot match
53 @samp{/} in @var{string}.  Thus, the only way to match @samp{/} is with
54 an explicit @samp{/} in @var{pattern}.
56 @comment fnmatch.h
57 @comment POSIX.2
58 @item FNM_PATHNAME
59 This is an alias for @code{FNM_FILE_NAME}; it comes from POSIX.2.  We
60 don't recommend this name because we don't use the term ``pathname'' for
61 file names.
63 @comment fnmatch.h
64 @comment POSIX.2
65 @item FNM_PERIOD
66 Treat the @samp{.} character specially if it appears at the beginning of
67 @var{string}.  If this flag is set, wildcard constructs in @var{pattern}
68 cannot match @samp{.} as the first character of @var{string}.
70 If you set both @code{FNM_PERIOD} and @code{FNM_FILE_NAME}, then the
71 special treatment applies to @samp{.} following @samp{/} as well as to
72 @samp{.} at the beginning of @var{string}.  (The shell uses the
73 @code{FNM_PERIOD} and @code{FNM_FILE_NAME} flags together for matching
74 file names.)
76 @comment fnmatch.h
77 @comment POSIX.2
78 @item FNM_NOESCAPE
79 Don't treat the @samp{\} character specially in patterns.  Normally,
80 @samp{\} quotes the following character, turning off its special meaning
81 (if any) so that it matches only itself.  When quoting is enabled, the
82 pattern @samp{\?} matches only the string @samp{?}, because the question
83 mark in the pattern acts like an ordinary character.
85 If you use @code{FNM_NOESCAPE}, then @samp{\} is an ordinary character.
87 @comment fnmatch.h
88 @comment GNU
89 @item FNM_LEADING_DIR
90 Ignore a trailing sequence of characters starting with a @samp{/} in
91 @var{string}; that is to say, test whether @var{string} starts with a
92 directory name that @var{pattern} matches.
94 If this flag is set, either @samp{foo*} or @samp{foobar} as a pattern
95 would match the string @samp{foobar/frobozz}.
97 @comment fnmatch.h
98 @comment GNU
99 @item FNM_CASEFOLD
100 Ignore case in comparing @var{string} to @var{pattern}.
101 @end table
103 @node Globbing
104 @section Globbing
106 @cindex globbing
107 The archetypal use of wildcards is for matching against the files in a
108 directory, and making a list of all the matches.  This is called
109 @dfn{globbing}.
111 You could do this using @code{fnmatch}, by reading the directory entries
112 one by one and testing each one with @code{fnmatch}.  But that would be
113 slow (and complex, since you would have to handle subdirectories by
114 hand).
116 The library provides a function @code{glob} to make this particular use
117 of wildcards convenient.  @code{glob} and the other symbols in this
118 section are declared in @file{glob.h}.
120 @menu
121 * Calling Glob::        Basic use of @code{glob}.
122 * Flags for Globbing::  Flags that enable various options in @code{glob}.
123 @end menu
125 @node Calling Glob
126 @subsection Calling @code{glob}
128 The result of globbing is a vector of file names (strings).  To return
129 this vector, @code{glob} uses a special data type, @code{glob_t}, which
130 is a structure.  You pass @code{glob} the address of the structure, and
131 it fills in the structure's fields to tell you about the results.
133 @comment glob.h
134 @comment POSIX.2
135 @deftp {Data Type} glob_t
136 This data type holds a pointer to a word vector.  More precisely, it
137 records both the address of the word vector and its size.
139 @table @code
140 @item gl_pathc
141 The number of elements in the vector.
143 @item gl_pathv
144 The address of the vector.  This field has type @w{@code{char **}}.
146 @item gl_offs
147 The offset of the first real element of the vector, from its nominal
148 address in the @code{gl_pathv} field.  Unlike the other fields, this
149 is always an input to @code{glob}, rather than an output from it.
151 If you use a nonzero offset, then that many elements at the beginning of
152 the vector are left empty.  (The @code{glob} function fills them with
153 null pointers.)
155 The @code{gl_offs} field is meaningful only if you use the
156 @code{GLOB_DOOFFS} flag.  Otherwise, the offset is always zero
157 regardless of what is in this field, and the first real element comes at
158 the beginning of the vector.
159 @end table
160 @end deftp
162 @comment glob.h
163 @comment POSIX.2
164 @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})
165 The function @code{glob} does globbing using the pattern @var{pattern}
166 in the current directory.  It puts the result in a newly allocated
167 vector, and stores the size and address of this vector into
168 @code{*@var{vector-ptr}}.  The argument @var{flags} is a combination of
169 bit flags; see @ref{Flags for Globbing}, for details of the flags.
171 The result of globbing is a sequence of file names.  The function
172 @code{glob} allocates a string for each resulting word, then
173 allocates a vector of type @code{char **} to store the addresses of
174 these strings.  The last element of the vector is a null pointer.
175 This vector is called the @dfn{word vector}.
177 To return this vector, @code{glob} stores both its address and its
178 length (number of elements, not counting the terminating null pointer)
179 into @code{*@var{vector-ptr}}.
181 Normally, @code{glob} sorts the file names alphabetically before
182 returning them.  You can turn this off with the flag @code{GLOB_NOSORT}
183 if you want to get the information as fast as possible.  Usually it's
184 a good idea to let @code{glob} sort them---if you process the files in
185 alphabetical order, the users will have a feel for the rate of progress
186 that your application is making.
188 If @code{glob} succeeds, it returns 0.  Otherwise, it returns one
189 of these error codes:
191 @table @code
192 @comment glob.h
193 @comment POSIX.2
194 @item GLOB_ABORTED
195 There was an error opening a directory, and you used the flag
196 @code{GLOB_ERR} or your specified @var{errfunc} returned a nonzero
197 value.
198 @iftex
199 See below
200 @end iftex
201 @ifinfo
202 @xref{Flags for Globbing},
203 @end ifinfo
204 for an explanation of the @code{GLOB_ERR} flag and @var{errfunc}.
206 @comment glob.h
207 @comment POSIX.2
208 @item GLOB_NOMATCH
209 The pattern didn't match any existing files.  If you use the
210 @code{GLOB_NOCHECK} flag, then you never get this error code, because
211 that flag tells @code{glob} to @emph{pretend} that the pattern matched
212 at least one file.
214 @comment glob.h
215 @comment POSIX.2
216 @item GLOB_NOSPACE
217 It was impossible to allocate memory to hold the result.
218 @end table
220 In the event of an error, @code{glob} stores information in
221 @code{*@var{vector-ptr}} about all the matches it has found so far.
222 @end deftypefun
224 @node Flags for Globbing
225 @subsection Flags for Globbing
227 This section describes the flags that you can specify in the
228 @var{flags} argument to @code{glob}.  Choose the flags you want,
229 and combine them with the C bitwise OR operator @code{|}.
231 @table @code
232 @comment glob.h
233 @comment POSIX.2
234 @item GLOB_APPEND
235 Append the words from this expansion to the vector of words produced by
236 previous calls to @code{glob}.  This way you can effectively expand
237 several words as if they were concatenated with spaces between them.
239 In order for appending to work, you must not modify the contents of the
240 word vector structure between calls to @code{glob}.  And, if you set
241 @code{GLOB_DOOFFS} in the first call to @code{glob}, you must also
242 set it when you append to the results.
244 Note that the pointer stored in @code{gl_pathv} may no longer be valid
245 after you call @code{glob} the second time, because @code{glob} might
246 have relocated the vector.  So always fetch @code{gl_pathv} from the
247 @code{glob_t} structure after each @code{glob} call; @strong{never} save
248 the pointer across calls.
250 @comment glob.h
251 @comment POSIX.2
252 @item GLOB_DOOFFS
253 Leave blank slots at the beginning of the vector of words.
254 The @code{gl_offs} field says how many slots to leave.
255 The blank slots contain null pointers.
257 @comment glob.h
258 @comment POSIX.2
259 @item GLOB_ERR
260 Give up right away and report an error if there is any difficulty
261 reading the directories that must be read in order to expand @var{pattern}
262 fully.  Such difficulties might include a directory in which you don't
263 have the requisite access.  Normally, @code{glob} tries its best to keep
264 on going despite any errors, reading whatever directories it can.
266 You can exercise even more control than this by specifying an
267 error-handler function @var{errfunc} when you call @code{glob}.  If
268 @var{errfunc} is not a null pointer, then @code{glob} doesn't give up
269 right away when it can't read a directory; instead, it calls
270 @var{errfunc} with two arguments, like this:
272 @smallexample
273 (*@var{errfunc}) (@var{filename}, @var{error-code})
274 @end smallexample
276 @noindent
277 The argument @var{filename} is the name of the directory that
278 @code{glob} couldn't open or couldn't read, and @var{error-code} is the
279 @code{errno} value that was reported to @code{glob}.
281 If the error handler function returns nonzero, then @code{glob} gives up
282 right away.  Otherwise, it continues.
284 @comment glob.h
285 @comment POSIX.2
286 @item GLOB_MARK
287 If the pattern matches the name of a directory, append @samp{/} to the
288 directory's name when returning it.
290 @comment glob.h
291 @comment POSIX.2
292 @item GLOB_NOCHECK
293 If the pattern doesn't match any file names, return the pattern itself
294 as if it were a file name that had been matched.  (Normally, when the
295 pattern doesn't match anything, @code{glob} returns that there were no
296 matches.)
298 @comment glob.h
299 @comment POSIX.2
300 @item GLOB_NOSORT
301 Don't sort the file names; return them in no particular order.
302 (In practice, the order will depend on the order of the entries in
303 the directory.)  The only reason @emph{not} to sort is to save time.
305 @comment glob.h
306 @comment POSIX.2
307 @item GLOB_NOESCAPE
308 Don't treat the @samp{\} character specially in patterns.  Normally,
309 @samp{\} quotes the following character, turning off its special meaning
310 (if any) so that it matches only itself.  When quoting is enabled, the
311 pattern @samp{\?} matches only the string @samp{?}, because the question
312 mark in the pattern acts like an ordinary character.
314 If you use @code{GLOB_NOESCAPE}, then @samp{\} is an ordinary character.
316 @code{glob} does its work by calling the function @code{fnmatch}
317 repeatedly.  It handles the flag @code{GLOB_NOESCAPE} by turning on the
318 @code{FNM_NOESCAPE} flag in calls to @code{fnmatch}.
319 @end table
321 @node Regular Expressions
322 @section Regular Expression Matching
324 The GNU C library supports two interfaces for matching regular
325 expressions.  One is the standard POSIX.2 interface, and the other is
326 what the GNU system has had for many years.
328 Both interfaces are declared in the header file @file{regex.h}.
329 If you define @w{@code{_POSIX_C_SOURCE}}, then only the POSIX.2
330 functions, structures, and constants are declared.
331 @c !!! we only document the POSIX.2 interface here!!
333 @menu
334 * POSIX Regexp Compilation::    Using @code{regcomp} to prepare to match.
335 * Flags for POSIX Regexps::     Syntax variations for @code{regcomp}.
336 * Matching POSIX Regexps::      Using @code{regexec} to match the compiled
337                                    pattern that you get from @code{regcomp}.
338 * Regexp Subexpressions::       Finding which parts of the string were matched.
339 * Subexpression Complications:: Find points of which parts were matched.
340 * Regexp Cleanup::              Freeing storage; reporting errors.
341 @end menu
343 @node POSIX Regexp Compilation
344 @subsection POSIX Regular Expression Compilation
346 Before you can actually match a regular expression, you must
347 @dfn{compile} it.  This is not true compilation---it produces a special
348 data structure, not machine instructions.  But it is like ordinary
349 compilation in that its purpose is to enable you to ``execute'' the
350 pattern fast.  (@xref{Matching POSIX Regexps}, for how to use the
351 compiled regular expression for matching.)
353 There is a special data type for compiled regular expressions:
355 @comment regex.h
356 @comment POSIX.2
357 @deftp {Data Type} regex_t
358 This type of object holds a compiled regular expression.
359 It is actually a structure.  It has just one field that your programs
360 should look at:
362 @table @code
363 @item re_nsub
364 This field holds the number of parenthetical subexpressions in the
365 regular expression that was compiled.
366 @end table
368 There are several other fields, but we don't describe them here, because
369 only the functions in the library should use them.
370 @end deftp
372 After you create a @code{regex_t} object, you can compile a regular
373 expression into it by calling @code{regcomp}.
375 @comment regex.h
376 @comment POSIX.2
377 @deftypefun int regcomp (regex_t *@var{compiled}, const char *@var{pattern}, int @var{cflags})
378 The function @code{regcomp} ``compiles'' a regular expression into a
379 data structure that you can use with @code{regexec} to match against a
380 string.  The compiled regular expression format is designed for
381 efficient matching.  @code{regcomp} stores it into @code{*@var{compiled}}.
383 It's up to you to allocate an object of type @code{regex_t} and pass its
384 address to @code{regcomp}.
386 The argument @var{cflags} lets you specify various options that control
387 the syntax and semantics of regular expressions.  @xref{Flags for POSIX
388 Regexps}.
390 If you use the flag @code{REG_NOSUB}, then @code{regcomp} omits from
391 the compiled regular expression the information necessary to record
392 how subexpressions actually match.  In this case, you might as well
393 pass @code{0} for the @var{matchptr} and @var{nmatch} arguments when
394 you call @code{regexec}.
396 If you don't use @code{REG_NOSUB}, then the compiled regular expression
397 does have the capacity to record how subexpressions match.  Also,
398 @code{regcomp} tells you how many subexpressions @var{pattern} has, by
399 storing the number in @code{@var{compiled}->re_nsub}.  You can use that
400 value to decide how long an array to allocate to hold information about
401 subexpression matches.
403 @code{regcomp} returns @code{0} if it succeeds in compiling the regular
404 expression; otherwise, it returns a nonzero error code (see the table
405 below).  You can use @code{regerror} to produce an error message string
406 describing the reason for a nonzero value; see @ref{Regexp Cleanup}.
408 @end deftypefun
410 Here are the possible nonzero values that @code{regcomp} can return:
412 @table @code
413 @comment regex.h
414 @comment POSIX.2
415 @item REG_BADBR
416 There was an invalid @samp{\@{@dots{}\@}} construct in the regular
417 expression.  A valid @samp{\@{@dots{}\@}} construct must contain either
418 a single number, or two numbers in increasing order separated by a
419 comma.
421 @comment regex.h
422 @comment POSIX.2
423 @item REG_BADPAT
424 There was a syntax error in the regular expression.
426 @comment regex.h
427 @comment POSIX.2
428 @item REG_BADRPT
429 A repetition operator such as @samp{?} or @samp{*} appeared in a bad
430 position (with no preceding subexpression to act on).
432 @comment regex.h
433 @comment POSIX.2
434 @item REG_ECOLLATE
435 The regular expression referred to an invalid collating element (one not
436 defined in the current locale for string collation).  @xref{Locale
437 Categories}.
439 @comment regex.h
440 @comment POSIX.2
441 @item REG_ECTYPE
442 The regular expression referred to an invalid character class name.
444 @comment regex.h
445 @comment POSIX.2
446 @item REG_EESCAPE
447 The regular expression ended with @samp{\}.
449 @comment regex.h
450 @comment POSIX.2
451 @item REG_ESUBREG
452 There was an invalid number in the @samp{\@var{digit}} construct.
454 @comment regex.h
455 @comment POSIX.2
456 @item REG_EBRACK
457 There were unbalanced square brackets in the regular expression.
459 @comment regex.h
460 @comment POSIX.2
461 @item REG_EPAREN
462 An extended regular expression had unbalanced parentheses,
463 or a basic regular expression had unbalanced @samp{\(} and @samp{\)}.
465 @comment regex.h
466 @comment POSIX.2
467 @item REG_EBRACE
468 The regular expression had unbalanced @samp{\@{} and @samp{\@}}.
470 @comment regex.h
471 @comment POSIX.2
472 @item REG_ERANGE
473 One of the endpoints in a range expression was invalid.
475 @comment regex.h
476 @comment POSIX.2
477 @item REG_ESPACE
478 @code{regcomp} ran out of memory.
479 @end table
481 @node Flags for POSIX Regexps
482 @subsection Flags for POSIX Regular Expressions
484 These are the bit flags that you can use in the @var{cflags} operand when
485 compiling a regular expression with @code{regcomp}.
487 @table @code
488 @comment regex.h
489 @comment POSIX.2
490 @item REG_EXTENDED
491 Treat the pattern as an extended regular expression, rather than as a
492 basic regular expression.
494 @comment regex.h
495 @comment POSIX.2
496 @item REG_ICASE
497 Ignore case when matching letters.
499 @comment regex.h
500 @comment POSIX.2
501 @item REG_NOSUB
502 Don't bother storing the contents of the @var{matches-ptr} array.
504 @comment regex.h
505 @comment POSIX.2
506 @item REG_NEWLINE
507 Treat a newline in @var{string} as dividing @var{string} into multiple
508 lines, so that @samp{$} can match before the newline and @samp{^} can
509 match after.  Also, don't permit @samp{.} to match a newline, and don't
510 permit @samp{[^@dots{}]} to match a newline.
512 Otherwise, newline acts like any other ordinary character.
513 @end table
515 @node Matching POSIX Regexps
516 @subsection Matching a Compiled POSIX Regular Expression
518 Once you have compiled a regular expression, as described in @ref{POSIX
519 Regexp Compilation}, you can match it against strings using
520 @code{regexec}.  A match anywhere inside the string counts as success,
521 unless the regular expression contains anchor characters (@samp{^} or
522 @samp{$}).
524 @comment regex.h
525 @comment POSIX.2
526 @deftypefun int regexec (regex_t *@var{compiled}, char *@var{string}, size_t @var{nmatch}, regmatch_t @var{matchptr} @t{[]}, int @var{eflags})
527 This function tries to match the compiled regular expression
528 @code{*@var{compiled}} against @var{string}.
530 @code{regexec} returns @code{0} if the regular expression matches;
531 otherwise, it returns a nonzero value.  See the table below for
532 what nonzero values mean.  You can use @code{regerror} to produce an
533 error message string describing the reason for a nonzero value;
534 see @ref{Regexp Cleanup}.
536 The argument @var{eflags} is a word of bit flags that enable various
537 options.
539 If you want to get information about what part of @var{string} actually
540 matched the regular expression or its subexpressions, use the arguments
541 @var{matchptr} and @var{nmatch}.  Otherwise, pass @code{0} for
542 @var{nmatch}, and @code{NULL} for @var{matchptr}.  @xref{Regexp
543 Subexpressions}.
544 @end deftypefun
546 You must match the regular expression with the same set of current
547 locales that were in effect when you compiled the regular expression.
549 The function @code{regexec} accepts the following flags in the
550 @var{eflags} argument:
552 @table @code
553 @comment regex.h
554 @comment POSIX.2
555 @item REG_NOTBOL
556 Do not regard the beginning of the specified string as the beginning of
557 a line; more generally, don't make any assumptions about what text might
558 precede it.
560 @comment regex.h
561 @comment POSIX.2
562 @item REG_NOTEOL
563 Do not regard the end of the specified string as the end of a line; more
564 generally, don't make any assumptions about what text might follow it.
565 @end table
567 Here are the possible nonzero values that @code{regexec} can return:
569 @table @code
570 @comment regex.h
571 @comment POSIX.2
572 @item REG_NOMATCH
573 The pattern didn't match the string.  This isn't really an error.
575 @comment regex.h
576 @comment POSIX.2
577 @item REG_ESPACE
578 @code{regexec} ran out of memory.
579 @end table
581 @node Regexp Subexpressions
582 @subsection Match Results with Subexpressions
584 When @code{regexec} matches parenthetical subexpressions of
585 @var{pattern}, it records which parts of @var{string} they match.  It
586 returns that information by storing the offsets into an array whose
587 elements are structures of type @code{regmatch_t}.  The first element of
588 the array (index @code{0}) records the part of the string that matched
589 the entire regular expression.  Each other element of the array records
590 the beginning and end of the part that matched a single parenthetical
591 subexpression.
593 @comment regex.h
594 @comment POSIX.2
595 @deftp {Data Type} regmatch_t
596 This is the data type of the @var{matcharray} array that you pass to
597 @code{regexec}.  It contains two structure fields, as follows:
599 @table @code
600 @item rm_so
601 The offset in @var{string} of the beginning of a substring.  Add this
602 value to @var{string} to get the address of that part.
604 @item rm_eo
605 The offset in @var{string} of the end of the substring.
606 @end table
607 @end deftp
609 @comment regex.h
610 @comment POSIX.2
611 @deftp {Data Type} regoff_t
612 @code{regoff_t} is an alias for another signed integer type.
613 The fields of @code{regmatch_t} have type @code{regoff_t}.
614 @end deftp
616 The @code{regmatch_t} elements correspond to subexpressions
617 positionally; the first element (index @code{1}) records where the first
618 subexpression matched, the second element records the second
619 subexpression, and so on.  The order of the subexpressions is the order
620 in which they begin.
622 When you call @code{regexec}, you specify how long the @var{matchptr}
623 array is, with the @var{nmatch} argument.  This tells @code{regexec} how
624 many elements to store.  If the actual regular expression has more than
625 @var{nmatch} subexpressions, then you won't get offset information about
626 the rest of them.  But this doesn't alter whether the pattern matches a
627 particular string or not.
629 If you don't want @code{regexec} to return any information about where
630 the subexpressions matched, you can either supply @code{0} for
631 @var{nmatch}, or use the flag @code{REG_NOSUB} when you compile the
632 pattern with @code{regcomp}.
634 @node Subexpression Complications
635 @subsection Complications in Subexpression Matching
637 Sometimes a subexpression matches a substring of no characters.  This
638 happens when @samp{f\(o*\)} matches the string @samp{fum}.  (It really
639 matches just the @samp{f}.)  In this case, both of the offsets identify
640 the point in the string where the null substring was found.  In this
641 example, the offsets are both @code{1}.
643 Sometimes the entire regular expression can match without using some of
644 its subexpressions at all---for example, when @samp{ba\(na\)*} matches the
645 string @samp{ba}, the parenthetical subexpression is not used.  When
646 this happens, @code{regexec} stores @code{-1} in both fields of the
647 element for that subexpression.
649 Sometimes matching the entire regular expression can match a particular
650 subexpression more than once---for example, when @samp{ba\(na\)*}
651 matches the string @samp{bananana}, the parenthetical subexpression
652 matches three times.  When this happens, @code{regexec} usually stores
653 the offsets of the last part of the string that matched the
654 subexpression.  In the case of @samp{bananana}, these offsets are
655 @code{6} and @code{8}.
657 But the last match is not always the one that is chosen.  It's more
658 accurate to say that the last @emph{opportunity} to match is the one
659 that takes precedence.  What this means is that when one subexpression
660 appears within another, then the results reported for the inner
661 subexpression reflect whatever happened on the last match of the outer
662 subexpression.  For an example, consider @samp{\(ba\(na\)*s \)*} matching
663 the string @samp{bananas bas }.  The last time the inner expression
664 actually matches is near the end of the first word.  But it is
665 @emph{considered} again in the second word, and fails to match there.
666 @code{regexec} reports nonuse of the ``na'' subexpression.
668 Another place where this rule applies is when the regular expression
669 @w{@samp{\(ba\(na\)*s \|nefer\(ti\)* \)*}} matches @samp{bananas nefertiti}.
670 The ``na'' subexpression does match in the first word, but it doesn't
671 match in the second word because the other alternative is used there.
672 Once again, the second repetition of the outer subexpression overrides
673 the first, and within that second repetition, the ``na'' subexpression
674 is not used.  So @code{regexec} reports nonuse of the ``na''
675 subexpression.
677 @node Regexp Cleanup
678 @subsection POSIX Regexp Matching Cleanup
680 When you are finished using a compiled regular expression, you can
681 free the storage it uses by calling @code{regfree}.
683 @comment regex.h
684 @comment POSIX.2
685 @deftypefun void regfree (regex_t *@var{compiled})
686 Calling @code{regfree} frees all the storage that @code{*@var{compiled}}
687 points to.  This includes various internal fields of the @code{regex_t}
688 structure that aren't documented in this manual.
690 @code{regfree} does not free the object @code{*@var{compiled}} itself.
691 @end deftypefun
693 You should always free the space in a @code{regex_t} structure with
694 @code{regfree} before using the structure to compile another regular
695 expression.
697 When @code{regcomp} or @code{regexec} reports an error, you can use
698 the function @code{regerror} to turn it into an error message string.
700 @comment regex.h
701 @comment POSIX.2
702 @deftypefun size_t regerror (int @var{errcode}, regex_t *@var{compiled}, char *@var{buffer}, size_t @var{length})
703 This function produces an error message string for the error code
704 @var{errcode}, and stores the string in @var{length} bytes of memory
705 starting at @var{buffer}.  For the @var{compiled} argument, supply the
706 same compiled regular expression structure that @code{regcomp} or
707 @code{regexec} was working with when it got the error.  Alternatively,
708 you can supply @code{NULL} for @var{compiled}; you will still get a
709 meaningful error message, but it might not be as detailed.
711 If the error message can't fit in @var{length} bytes (including a
712 terminating null character), then @code{regerror} truncates it.
713 The string that @code{regerror} stores is always null-terminated
714 even if it has been truncated.
716 The return value of @code{regerror} is the minimum length needed to
717 store the entire error message.  If this is less than @var{length}, then
718 the error message was not truncated, and you can use it.  Otherwise, you
719 should call @code{regerror} again with a larger buffer.
721 Here is a function which uses @code{regerror}, but always dynamically
722 allocates a buffer for the error message:
724 @smallexample
725 char *get_regerror (int errcode, regex_t *compiled)
727   size_t length = regerror (errcode, compiled, NULL, 0);
728   char *buffer = xmalloc (length);
729   (void) regerror (errcode, compiled, buffer, length);
730   return buffer;
732 @end smallexample
733 @end deftypefun
735 @c !!!! this is not actually in the library....
736 @node Word Expansion
737 @section Shell-Style Word Expansion
738 @cindex word expansion
739 @cindex expansion of shell words
741 @dfn{Word expansion} means the process of splitting a string into
742 @dfn{words} and substituting for variables, commands, and wildcards
743 just as the shell does.
745 For example, when you write @samp{ls -l foo.c}, this string is split
746 into three separate words---@samp{ls}, @samp{-l} and @samp{foo.c}.
747 This is the most basic function of word expansion.
749 When you write @samp{ls *.c}, this can become many words, because
750 the word @samp{*.c} can be replaced with any number of file names.
751 This is called @dfn{wildcard expansion}, and it is also a part of
752 word expansion.
754 When you use @samp{echo $PATH} to print your path, you are taking
755 advantage of @dfn{variable substitution}, which is also part of word
756 expansion.
758 Ordinary programs can perform word expansion just like the shell by
759 calling the library function @code{wordexp}.
761 @menu
762 * Expansion Stages::    What word expansion does to a string.
763 * Calling Wordexp::     How to call @code{wordexp}.
764 * Flags for Wordexp::   Options you can enable in @code{wordexp}.
765 * Wordexp Example::     A sample program that does word expansion.
766 @end menu
768 @node Expansion Stages
769 @subsection The Stages of Word Expansion
771 When word expansion is applied to a sequence of words, it performs the
772 following transformations in the order shown here:
774 @enumerate
775 @item
776 @cindex tilde expansion
777 @dfn{Tilde expansion}: Replacement of @samp{~foo} with the name of
778 the home directory of @samp{foo}.
780 @item
781 Next, three different transformations are applied in the same step,
782 from left to right:
784 @itemize @bullet
785 @item
786 @cindex variable substitution
787 @cindex substitution of variables and commands
788 @dfn{Variable substitution}: Environment variables are substituted for
789 references such as @samp{$foo}.
791 @item
792 @cindex command substitution
793 @dfn{Command substitution}: Constructs such as @w{@samp{`cat foo`}} and
794 the equivalent @w{@samp{$(cat foo)}} are replaced with the output from
795 the inner command.
797 @item
798 @cindex arithmetic expansion
799 @dfn{Arithmetic expansion}: Constructs such as @samp{$(($x-1))} are
800 replaced with the result of the arithmetic computation.
801 @end itemize
803 @item
804 @cindex field splitting
805 @dfn{Field splitting}: subdivision of the text into @dfn{words}.
807 @item
808 @cindex wildcard expansion
809 @dfn{Wildcard expansion}: The replacement of a construct such as @samp{*.c}
810 with a list of @samp{.c} file names.  Wildcard expansion applies to an
811 entire word at a time, and replaces that word with 0 or more file names
812 that are themselves words.
814 @item
815 @cindex quote removal
816 @cindex removal of quotes
817 @dfn{Quote removal}: The deletion of string-quotes, now that they have
818 done their job by inhibiting the above transformations when appropriate.
819 @end enumerate
821 For the details of these transformations, and how to write the constructs
822 that use them, see @w{@cite{The BASH Manual}} (to appear).
824 @node Calling Wordexp
825 @subsection Calling @code{wordexp}
827 All the functions, constants and data types for word expansion are
828 declared in the header file @file{wordexp.h}.
830 Word expansion produces a vector of words (strings).  To return this
831 vector, @code{wordexp} uses a special data type, @code{wordexp_t}, which
832 is a structure.  You pass @code{wordexp} the address of the structure,
833 and it fills in the structure's fields to tell you about the results.
835 @comment wordexp.h
836 @comment POSIX.2
837 @deftp {Data Type} {wordexp_t}
838 This data type holds a pointer to a word vector.  More precisely, it
839 records both the address of the word vector and its size.
841 @table @code
842 @item we_wordc
843 The number of elements in the vector.
845 @item we_wordv
846 The address of the vector.  This field has type @w{@code{char **}}.
848 @item we_offs
849 The offset of the first real element of the vector, from its nominal
850 address in the @code{we_wordv} field.  Unlike the other fields, this
851 is always an input to @code{wordexp}, rather than an output from it.
853 If you use a nonzero offset, then that many elements at the beginning of
854 the vector are left empty.  (The @code{wordexp} function fills them with
855 null pointers.)
857 The @code{we_offs} field is meaningful only if you use the
858 @code{WRDE_DOOFFS} flag.  Otherwise, the offset is always zero
859 regardless of what is in this field, and the first real element comes at
860 the beginning of the vector.
861 @end table
862 @end deftp
864 @comment wordexp.h
865 @comment POSIX.2
866 @deftypefun int wordexp (const char *@var{words}, wordexp_t *@var{word-vector-ptr}, int @var{flags})
867 Perform word expansion on the string @var{words}, putting the result in
868 a newly allocated vector, and store the size and address of this vector
869 into @code{*@var{word-vector-ptr}}.  The argument @var{flags} is a
870 combination of bit flags; see @ref{Flags for Wordexp}, for details of
871 the flags.
873 You shouldn't use any of the characters @samp{|&;<>} in the string
874 @var{words} unless they are quoted; likewise for newline.  If you use
875 these characters unquoted, you will get the @code{WRDE_BADCHAR} error
876 code.  Don't use parentheses or braces unless they are quoted or part of
877 a word expansion construct.  If you use quotation characters @samp{'"`},
878 they should come in pairs that balance.
880 The results of word expansion are a sequence of words.  The function
881 @code{wordexp} allocates a string for each resulting word, then
882 allocates a vector of type @code{char **} to store the addresses of
883 these strings.  The last element of the vector is a null pointer.
884 This vector is called the @dfn{word vector}.
886 To return this vector, @code{wordexp} stores both its address and its
887 length (number of elements, not counting the terminating null pointer)
888 into @code{*@var{word-vector-ptr}}.
890 If @code{wordexp} succeeds, it returns 0.  Otherwise, it returns one
891 of these error codes:
893 @table @code
894 @comment wordexp.h
895 @comment POSIX.2
896 @item WRDE_BADCHAR
897 The input string @var{words} contains an unquoted invalid character such
898 as @samp{|}.
900 @comment wordexp.h
901 @comment POSIX.2
902 @item WRDE_BADVAL
903 The input string refers to an undefined shell variable, and you used the flag
904 @code{WRDE_UNDEF} to forbid such references.
906 @comment wordexp.h
907 @comment POSIX.2
908 @item WRDE_CMDSUB
909 The input string uses command substitution, and you used the flag
910 @code{WRDE_NOCMD} to forbid command substitution.
912 @comment wordexp.h
913 @comment POSIX.2
914 @item WRDE_NOSPACE
915 It was impossible to allocate memory to hold the result.  In this case,
916 @code{wordexp} can store part of the results---as much as it could
917 allocate room for.
919 @comment wordexp.h
920 @comment POSIX.2
921 @item WRDE_SYNTAX
922 There was a syntax error in the input string.  For example, an unmatched
923 quoting character is a syntax error.
924 @end table
925 @end deftypefun
927 @comment wordexp.h
928 @comment POSIX.2
929 @deftypefun void wordfree (wordexp_t *@var{word-vector-ptr})
930 Free the storage used for the word-strings and vector that
931 @code{*@var{word-vector-ptr}} points to.  This does not free the
932 structure @code{*@var{word-vector-ptr}} itself---only the other
933 data it points to.
934 @end deftypefun
936 @node Flags for Wordexp
937 @subsection Flags for Word Expansion
939 This section describes the flags that you can specify in the
940 @var{flags} argument to @code{wordexp}.  Choose the flags you want,
941 and combine them with the C operator @code{|}.
943 @table @code
944 @comment wordexp.h
945 @comment POSIX.2
946 @item WRDE_APPEND
947 Append the words from this expansion to the vector of words produced by
948 previous calls to @code{wordexp}.  This way you can effectively expand
949 several words as if they were concatenated with spaces between them.
951 In order for appending to work, you must not modify the contents of the
952 word vector structure between calls to @code{wordexp}.  And, if you set
953 @code{WRDE_DOOFFS} in the first call to @code{wordexp}, you must also
954 set it when you append to the results.
956 @comment wordexp.h
957 @comment POSIX.2
958 @item WRDE_DOOFFS
959 Leave blank slots at the beginning of the vector of words.
960 The @code{we_offs} field says how many slots to leave.
961 The blank slots contain null pointers.
963 @comment wordexp.h
964 @comment POSIX.2
965 @item WRDE_NOCMD
966 Don't do command substitution; if the input requests command substitution,
967 report an error.
969 @comment wordexp.h
970 @comment POSIX.2
971 @item WRDE_REUSE
972 Reuse a word vector made by a previous call to @code{wordexp}.
973 Instead of allocating a new vector of words, this call to @code{wordexp}
974 will use the vector that already exists (making it larger if necessary).
976 Note that the vector may move, so it is not safe to save an old pointer
977 and use it again after calling @code{wordexp}.  You must fetch
978 @code{we_pathv} anew after each call.
980 @comment wordexp.h
981 @comment POSIX.2
982 @item WRDE_SHOWERR
983 Do show any error messages printed by commands run by command substitution.
984 More precisely, allow these commands to inherit the standard error output
985 stream of the current process.  By default, @code{wordexp} gives these
986 commands a standard error stream that discards all output.
988 @comment wordexp.h
989 @comment POSIX.2
990 @item WRDE_UNDEF
991 If the input refers to a shell variable that is not defined, report an
992 error.
993 @end table
995 @node Wordexp Example
996 @subsection @code{wordexp} Example
998 Here is an example of using @code{wordexp} to expand several strings
999 and use the results to run a shell command.  It also shows the use of
1000 @code{WRDE_APPEND} to concatenate the expansions and of @code{wordfree}
1001 to free the space allocated by @code{wordexp}.
1003 @smallexample
1005 expand_and_execute (const char *program, const char *options)
1007   wordexp_t result;
1008   pid_t pid
1009   int status, i;
1011   /* @r{Expand the string for the program to run.}  */
1012   switch (wordexp (program, &result, 0))
1013     @{
1014     case 0:                     /* @r{Successful}.  */
1015       break;
1016     case WRDE_NOSPACE:
1017       /* @r{If the error was @code{WRDE_NOSPACE},}
1018          @r{then perhaps part of the result was allocated.}  */
1019       wordfree (&result);
1020     default:                    /* @r{Some other error.}  */
1021       return -1;
1022     @}
1024   /* @r{Expand the strings specified for the arguments.}  */
1025   for (i = 0; args[i]; i++)
1026     @{
1027       if (wordexp (options, &result, WRDE_APPEND))
1028         @{
1029           wordfree (&result);
1030           return -1;
1031         @}
1032     @}
1034   pid = fork ();
1035   if (pid == 0)
1036     @{
1037       /* @r{This is the child process.  Execute the command.} */
1038       execv (result.we_wordv[0], result.we_wordv);
1039       exit (EXIT_FAILURE);
1040     @}
1041   else if (pid < 0)
1042     /* @r{The fork failed.  Report failure.}  */
1043     status = -1;
1044   else
1045     /* @r{This is the parent process.  Wait for the child to complete.}  */
1046     if (waitpid (pid, &status, 0) != pid)
1047       status = -1;
1049   wordfree (&result);
1050   return status;
1052 @end smallexample
1054 In practice, since @code{wordexp} is executed by running a subshell, it
1055 would be faster to do this by concatenating the strings with spaces
1056 between them and running that as a shell command using @samp{sh -c}.
1058 @c No sense finishing this for here.
1059 @ignore
1060 @node Tilde Expansion
1061 @subsection Details of Tilde Expansion
1063 It's a standard part of shell syntax that you can use @samp{~} at the
1064 beginning of a file name to stand for your own home directory.  You
1065 can use @samp{~@var{user}} to stand for @var{user}'s home directory.
1067 @dfn{Tilde expansion} is the process of converting these abbreviations
1068 to the directory names that they stand for.
1070 Tilde expansion applies to the @samp{~} plus all following characters up
1071 to whitespace or a slash.  It takes place only at the beginning of a
1072 word, and only if none of the characters to be transformed is quoted in
1073 any way.
1075 Plain @samp{~} uses the value of the environment variable @code{HOME}
1076 as the proper home directory name.  @samp{~} followed by a user name
1077 uses @code{getpwname} to look up that user in the user database, and
1078 uses whatever directory is recorded there.  Thus, @samp{~} followed
1079 by your own name can give different results from plain @samp{~}, if
1080 the value of @code{HOME} is not really your home directory.
1082 @node Variable Substitution
1083 @subsection Details of Variable Substitution
1085 Part of ordinary shell syntax is the use of @samp{$@var{variable}} to
1086 substitute the value of a shell variable into a command.  This is called
1087 @dfn{variable substitution}, and it is one part of doing word expansion.
1089 There are two basic ways you can write a variable reference for
1090 substitution:
1092 @table @code
1093 @item $@{@var{variable}@}
1094 If you write braces around the variable name, then it is completely
1095 unambiguous where the variable name ends.  You can concatenate
1096 additional letters onto the end of the variable value by writing them
1097 immediately after the close brace.  For example, @samp{$@{foo@}s}
1098 expands into @samp{tractors}.
1100 @item $@var{variable}
1101 If you do not put braces around the variable name, then the variable
1102 name consists of all the alphanumeric characters and underscores that
1103 follow the @samp{$}.  The next punctuation character ends the variable
1104 name.  Thus, @samp{$foo-bar} refers to the variable @code{foo} and expands
1105 into @samp{tractor-bar}.
1106 @end table
1108 When you use braces, you can also use various constructs to modify the
1109 value that is substituted, or test it in various ways.
1111 @table @code
1112 @item $@{@var{variable}:-@var{default}@}
1113 Substitute the value of @var{variable}, but if that is empty or
1114 undefined, use @var{default} instead.
1116 @item $@{@var{variable}:=@var{default}@}
1117 Substitute the value of @var{variable}, but if that is empty or
1118 undefined, use @var{default} instead and set the variable to
1119 @var{default}.
1121 @item $@{@var{variable}:?@var{message}@}
1122 If @var{variable} is defined and not empty, substitute its value.
1124 Otherwise, print @var{message} as an error message on the standard error
1125 stream, and consider word expansion a failure.
1127 @c ??? How does wordexp report such an error?
1129 @item $@{@var{variable}:+@var{replacement}@}
1130 Substitute @var{replacement}, but only if @var{variable} is defined and
1131 nonempty.  Otherwise, substitute nothing for this construct.
1132 @end table
1134 @table @code
1135 @item $@{#@var{variable}@}
1136 Substitute a numeral which expresses in base ten the number of
1137 characters in the value of @var{variable}.  @samp{$@{#foo@}} stands for
1138 @samp{7}, because @samp{tractor} is seven characters.
1139 @end table
1141 These variants of variable substitution let you remove part of the
1142 variable's value before substituting it.  The @var{prefix} and
1143 @var{suffix} are not mere strings; they are wildcard patterns, just
1144 like the patterns that you use to match multiple file names.  But
1145 in this context, they match against parts of the variable value
1146 rather than against file names.
1148 @table @code
1149 @item $@{@var{variable}%%@var{suffix}@}
1150 Substitute the value of @var{variable}, but first discard from that
1151 variable any portion at the end that matches the pattern @var{suffix}.
1153 If there is more than one alternative for how to match against
1154 @var{suffix}, this construct uses the longest possible match.
1156 Thus, @samp{$@{foo%%r*@}} substitutes @samp{t}, because the largest
1157 match for @samp{r*} at the end of @samp{tractor} is @samp{ractor}.
1159 @item $@{@var{variable}%@var{suffix}@}
1160 Substitute the value of @var{variable}, but first discard from that
1161 variable any portion at the end that matches the pattern @var{suffix}.
1163 If there is more than one alternative for how to match against
1164 @var{suffix}, this construct uses the shortest possible alternative.
1166 Thus, @samp{$@{foo%%r*@}} substitutes @samp{tracto}, because the shortest
1167 match for @samp{r*} at the end of @samp{tractor} is just @samp{r}.
1169 @item $@{@var{variable}##@var{prefix}@}
1170 Substitute the value of @var{variable}, but first discard from that
1171 variable any portion at the beginning that matches the pattern @var{prefix}.
1173 If there is more than one alternative for how to match against
1174 @var{prefix}, this construct uses the longest possible match.
1176 Thus, @samp{$@{foo%%r*@}} substitutes @samp{t}, because the largest
1177 match for @samp{r*} at the end of @samp{tractor} is @samp{ractor}.
1179 @item $@{@var{variable}#@var{prefix}@}
1180 Substitute the value of @var{variable}, but first discard from that
1181 variable any portion at the beginning that matches the pattern @var{prefix}.
1183 If there is more than one alternative for how to match against
1184 @var{prefix}, this construct uses the shortest possible alternative.
1186 Thus, @samp{$@{foo%%r*@}} substitutes @samp{tracto}, because the shortest
1187 match for @samp{r*} at the end of @samp{tractor} is just @samp{r}.
1189 @end ignore