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