2.9
[glibc/nacl-glibc.git] / manual / pattern.texi
blobc2a42cd843b788614513f31f7ea765cf030eece5
1 @node Pattern Matching, I/O Overview, Searching and Sorting, Top
2 @c %MENU% Matching shell ``globs'' and regular expressions
3 @chapter Pattern Matching
5 The GNU C Library provides pattern matching facilities for two kinds of
6 patterns: regular expressions and file-name wildcards.  The library also
7 provides a facility for expanding variable and command references and
8 parsing text into words in the way the shell does.
10 @menu
11 * Wildcard Matching::    Matching a wildcard pattern against a single string.
12 * Globbing::             Finding the files that match a wildcard pattern.
13 * Regular Expressions::  Matching regular expressions against strings.
14 * Word Expansion::       Expanding shell variables, nested commands,
15                             arithmetic, and wildcards.
16                             This is what the shell does with shell commands.
17 @end menu
19 @node Wildcard Matching
20 @section Wildcard Matching
22 @pindex fnmatch.h
23 This section describes how to match a wildcard pattern against a
24 particular string.  The result is a yes or no answer: does the
25 string fit the pattern or not.  The symbols described here are all
26 declared in @file{fnmatch.h}.
28 @comment fnmatch.h
29 @comment POSIX.2
30 @deftypefun int fnmatch (const char *@var{pattern}, const char *@var{string}, int @var{flags})
31 This function tests whether the string @var{string} matches the pattern
32 @var{pattern}.  It returns @code{0} if they do match; otherwise, it
33 returns the nonzero value @code{FNM_NOMATCH}.  The arguments
34 @var{pattern} and @var{string} are both strings.
36 The argument @var{flags} is a combination of flag bits that alter the
37 details of matching.  See below for a list of the defined flags.
39 In the GNU C Library, @code{fnmatch} cannot experience an ``error''---it
40 always returns an answer for whether the match succeeds.  However, other
41 implementations of @code{fnmatch} might sometimes report ``errors''.
42 They would do so by returning nonzero values that are not equal to
43 @code{FNM_NOMATCH}.
44 @end deftypefun
46 These are the available flags for the @var{flags} argument:
48 @table @code
49 @comment fnmatch.h
50 @comment GNU
51 @item FNM_FILE_NAME
52 Treat the @samp{/} character specially, for matching file names.  If
53 this flag is set, wildcard constructs in @var{pattern} cannot match
54 @samp{/} in @var{string}.  Thus, the only way to match @samp{/} is with
55 an explicit @samp{/} in @var{pattern}.
57 @comment fnmatch.h
58 @comment POSIX.2
59 @item FNM_PATHNAME
60 This is an alias for @code{FNM_FILE_NAME}; it comes from POSIX.2.  We
61 don't recommend this name because we don't use the term ``pathname'' for
62 file names.
64 @comment fnmatch.h
65 @comment POSIX.2
66 @item FNM_PERIOD
67 Treat the @samp{.} character specially if it appears at the beginning of
68 @var{string}.  If this flag is set, wildcard constructs in @var{pattern}
69 cannot match @samp{.} as the first character of @var{string}.
71 If you set both @code{FNM_PERIOD} and @code{FNM_FILE_NAME}, then the
72 special treatment applies to @samp{.} following @samp{/} as well as to
73 @samp{.} at the beginning of @var{string}.  (The shell uses the
74 @code{FNM_PERIOD} and @code{FNM_FILE_NAME} flags together for matching
75 file names.)
77 @comment fnmatch.h
78 @comment POSIX.2
79 @item FNM_NOESCAPE
80 Don't treat the @samp{\} character specially in patterns.  Normally,
81 @samp{\} quotes the following character, turning off its special meaning
82 (if any) so that it matches only itself.  When quoting is enabled, the
83 pattern @samp{\?} matches only the string @samp{?}, because the question
84 mark in the pattern acts like an ordinary character.
86 If you use @code{FNM_NOESCAPE}, then @samp{\} is an ordinary character.
88 @comment fnmatch.h
89 @comment GNU
90 @item FNM_LEADING_DIR
91 Ignore a trailing sequence of characters starting with a @samp{/} in
92 @var{string}; that is to say, test whether @var{string} starts with a
93 directory name that @var{pattern} matches.
95 If this flag is set, either @samp{foo*} or @samp{foobar} as a pattern
96 would match the string @samp{foobar/frobozz}.
98 @comment fnmatch.h
99 @comment GNU
100 @item FNM_CASEFOLD
101 Ignore case in comparing @var{string} to @var{pattern}.
103 @comment fnmatch.h
104 @comment GNU
105 @item FNM_EXTMATCH
106 @cindex Korn Shell
107 @pindex ksh
108 Recognize beside the normal patterns also the extended patterns
109 introduced in @file{ksh}.  The patterns are written in the form
110 explained in the following table where @var{pattern-list} is a @code{|}
111 separated list of patterns.
113 @table @code
114 @item ?(@var{pattern-list})
115 The pattern matches if zero or one occurrences of any of the patterns
116 in the @var{pattern-list} allow matching the input string.
118 @item *(@var{pattern-list})
119 The pattern matches if zero or more occurrences of any of the patterns
120 in the @var{pattern-list} allow matching the input string.
122 @item +(@var{pattern-list})
123 The pattern matches if one or more occurrences of any of the patterns
124 in the @var{pattern-list} allow matching the input string.
126 @item @@(@var{pattern-list})
127 The pattern matches if exactly one occurrence of any of the patterns in
128 the @var{pattern-list} allows matching the input string.
130 @item !(@var{pattern-list})
131 The pattern matches if the input string cannot be matched with any of
132 the patterns in the @var{pattern-list}.
133 @end table
134 @end table
136 @node Globbing
137 @section Globbing
139 @cindex globbing
140 The archetypal use of wildcards is for matching against the files in a
141 directory, and making a list of all the matches.  This is called
142 @dfn{globbing}.
144 You could do this using @code{fnmatch}, by reading the directory entries
145 one by one and testing each one with @code{fnmatch}.  But that would be
146 slow (and complex, since you would have to handle subdirectories by
147 hand).
149 The library provides a function @code{glob} to make this particular use
150 of wildcards convenient.  @code{glob} and the other symbols in this
151 section are declared in @file{glob.h}.
153 @menu
154 * Calling Glob::             Basic use of @code{glob}.
155 * Flags for Globbing::       Flags that enable various options in @code{glob}.
156 * More Flags for Globbing::  GNU specific extensions to @code{glob}.
157 @end menu
159 @node Calling Glob
160 @subsection Calling @code{glob}
162 The result of globbing is a vector of file names (strings).  To return
163 this vector, @code{glob} uses a special data type, @code{glob_t}, which
164 is a structure.  You pass @code{glob} the address of the structure, and
165 it fills in the structure's fields to tell you about the results.
167 @comment glob.h
168 @comment POSIX.2
169 @deftp {Data Type} glob_t
170 This data type holds a pointer to a word vector.  More precisely, it
171 records both the address of the word vector and its size.  The GNU
172 implementation contains some more fields which are non-standard
173 extensions.
175 @table @code
176 @item gl_pathc
177 The number of elements in the vector, excluding the initial null entries
178 if the GLOB_DOOFFS flag is used (see gl_offs below).
180 @item gl_pathv
181 The address of the vector.  This field has type @w{@code{char **}}.
183 @item gl_offs
184 The offset of the first real element of the vector, from its nominal
185 address in the @code{gl_pathv} field.  Unlike the other fields, this
186 is always an input to @code{glob}, rather than an output from it.
188 If you use a nonzero offset, then that many elements at the beginning of
189 the vector are left empty.  (The @code{glob} function fills them with
190 null pointers.)
192 The @code{gl_offs} field is meaningful only if you use the
193 @code{GLOB_DOOFFS} flag.  Otherwise, the offset is always zero
194 regardless of what is in this field, and the first real element comes at
195 the beginning of the vector.
197 @item gl_closedir
198 The address of an alternative implementation of the @code{closedir}
199 function.  It is used if the @code{GLOB_ALTDIRFUNC} bit is set in
200 the flag parameter.  The type of this field is
201 @w{@code{void (*) (void *)}}.
203 This is a GNU extension.
205 @item gl_readdir
206 The address of an alternative implementation of the @code{readdir}
207 function used to read the contents of a directory.  It is used if the
208 @code{GLOB_ALTDIRFUNC} bit is set in the flag parameter.  The type of
209 this field is @w{@code{struct dirent *(*) (void *)}}.
211 This is a GNU extension.
213 @item gl_opendir
214 The address of an alternative implementation of the @code{opendir}
215 function.  It is used if the @code{GLOB_ALTDIRFUNC} bit is set in
216 the flag parameter.  The type of this field is
217 @w{@code{void *(*) (const char *)}}.
219 This is a GNU extension.
221 @item gl_stat
222 The address of an alternative implementation of the @code{stat} function
223 to get information about an object in the filesystem.  It is used if the
224 @code{GLOB_ALTDIRFUNC} bit is set in the flag parameter.  The type of
225 this field is @w{@code{int (*) (const char *, struct stat *)}}.
227 This is a GNU extension.
229 @item gl_lstat
230 The address of an alternative implementation of the @code{lstat}
231 function to get information about an object in the filesystems, not
232 following symbolic links.  It is used if the @code{GLOB_ALTDIRFUNC} bit
233 is set in the flag parameter.  The type of this field is @code{@w{int
234 (*) (const char *,} @w{struct stat *)}}.
236 This is a GNU extension.
237 @end table
238 @end deftp
240 For use in the @code{glob64} function @file{glob.h} contains another
241 definition for a very similar type.  @code{glob64_t} differs from
242 @code{glob_t} only in the types of the members @code{gl_readdir},
243 @code{gl_stat}, and @code{gl_lstat}.
245 @comment glob.h
246 @comment GNU
247 @deftp {Data Type} glob64_t
248 This data type holds a pointer to a word vector.  More precisely, it
249 records both the address of the word vector and its size.  The GNU
250 implementation contains some more fields which are non-standard
251 extensions.
253 @table @code
254 @item gl_pathc
255 The number of elements in the vector, excluding the initial null entries
256 if the GLOB_DOOFFS flag is used (see gl_offs below).
258 @item gl_pathv
259 The address of the vector.  This field has type @w{@code{char **}}.
261 @item gl_offs
262 The offset of the first real element of the vector, from its nominal
263 address in the @code{gl_pathv} field.  Unlike the other fields, this
264 is always an input to @code{glob}, rather than an output from it.
266 If you use a nonzero offset, then that many elements at the beginning of
267 the vector are left empty.  (The @code{glob} function fills them with
268 null pointers.)
270 The @code{gl_offs} field is meaningful only if you use the
271 @code{GLOB_DOOFFS} flag.  Otherwise, the offset is always zero
272 regardless of what is in this field, and the first real element comes at
273 the beginning of the vector.
275 @item gl_closedir
276 The address of an alternative implementation of the @code{closedir}
277 function.  It is used if the @code{GLOB_ALTDIRFUNC} bit is set in
278 the flag parameter.  The type of this field is
279 @w{@code{void (*) (void *)}}.
281 This is a GNU extension.
283 @item gl_readdir
284 The address of an alternative implementation of the @code{readdir64}
285 function used to read the contents of a directory.  It is used if the
286 @code{GLOB_ALTDIRFUNC} bit is set in the flag parameter.  The type of
287 this field is @w{@code{struct dirent64 *(*) (void *)}}.
289 This is a GNU extension.
291 @item gl_opendir
292 The address of an alternative implementation of the @code{opendir}
293 function.  It is used if the @code{GLOB_ALTDIRFUNC} bit is set in
294 the flag parameter.  The type of this field is
295 @w{@code{void *(*) (const char *)}}.
297 This is a GNU extension.
299 @item gl_stat
300 The address of an alternative implementation of the @code{stat64} function
301 to get information about an object in the filesystem.  It is used if the
302 @code{GLOB_ALTDIRFUNC} bit is set in the flag parameter.  The type of
303 this field is @w{@code{int (*) (const char *, struct stat64 *)}}.
305 This is a GNU extension.
307 @item gl_lstat
308 The address of an alternative implementation of the @code{lstat64}
309 function to get information about an object in the filesystems, not
310 following symbolic links.  It is used if the @code{GLOB_ALTDIRFUNC} bit
311 is set in the flag parameter.  The type of this field is @code{@w{int
312 (*) (const char *,} @w{struct stat64 *)}}.
314 This is a GNU extension.
315 @end table
316 @end deftp
318 @comment glob.h
319 @comment POSIX.2
320 @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})
321 The function @code{glob} does globbing using the pattern @var{pattern}
322 in the current directory.  It puts the result in a newly allocated
323 vector, and stores the size and address of this vector into
324 @code{*@var{vector-ptr}}.  The argument @var{flags} is a combination of
325 bit flags; see @ref{Flags for Globbing}, for details of the flags.
327 The result of globbing is a sequence of file names.  The function
328 @code{glob} allocates a string for each resulting word, then
329 allocates a vector of type @code{char **} to store the addresses of
330 these strings.  The last element of the vector is a null pointer.
331 This vector is called the @dfn{word vector}.
333 To return this vector, @code{glob} stores both its address and its
334 length (number of elements, not counting the terminating null pointer)
335 into @code{*@var{vector-ptr}}.
337 Normally, @code{glob} sorts the file names alphabetically before
338 returning them.  You can turn this off with the flag @code{GLOB_NOSORT}
339 if you want to get the information as fast as possible.  Usually it's
340 a good idea to let @code{glob} sort them---if you process the files in
341 alphabetical order, the users will have a feel for the rate of progress
342 that your application is making.
344 If @code{glob} succeeds, it returns 0.  Otherwise, it returns one
345 of these error codes:
347 @vtable @code
348 @comment glob.h
349 @comment POSIX.2
350 @item GLOB_ABORTED
351 There was an error opening a directory, and you used the flag
352 @code{GLOB_ERR} or your specified @var{errfunc} returned a nonzero
353 value.
354 @iftex
355 See below
356 @end iftex
357 @ifinfo
358 @xref{Flags for Globbing},
359 @end ifinfo
360 for an explanation of the @code{GLOB_ERR} flag and @var{errfunc}.
362 @comment glob.h
363 @comment POSIX.2
364 @item GLOB_NOMATCH
365 The pattern didn't match any existing files.  If you use the
366 @code{GLOB_NOCHECK} flag, then you never get this error code, because
367 that flag tells @code{glob} to @emph{pretend} that the pattern matched
368 at least one file.
370 @comment glob.h
371 @comment POSIX.2
372 @item GLOB_NOSPACE
373 It was impossible to allocate memory to hold the result.
374 @end vtable
376 In the event of an error, @code{glob} stores information in
377 @code{*@var{vector-ptr}} about all the matches it has found so far.
379 It is important to notice that the @code{glob} function will not fail if
380 it encounters directories or files which cannot be handled without the
381 LFS interfaces.  The implementation of @code{glob} is supposed to use
382 these functions internally.  This at least is the assumptions made by
383 the Unix standard.  The GNU extension of allowing the user to provide
384 own directory handling and @code{stat} functions complicates things a
385 bit.  If these callback functions are used and a large file or directory
386 is encountered @code{glob} @emph{can} fail.
387 @end deftypefun
389 @comment glob.h
390 @comment GNU
391 @deftypefun int glob64 (const char *@var{pattern}, int @var{flags}, int (*@var{errfunc}) (const char *@var{filename}, int @var{error-code}), glob64_t *@var{vector-ptr})
392 The @code{glob64} function was added as part of the Large File Summit
393 extensions but is not part of the original LFS proposal.  The reason for
394 this is simple: it is not necessary.  The necessity for a @code{glob64}
395 function is added by the extensions of the GNU @code{glob}
396 implementation which allows the user to provide own directory handling
397 and @code{stat} functions.  The @code{readdir} and @code{stat} functions
398 do depend on the choice of @code{_FILE_OFFSET_BITS} since the definition
399 of the types @code{struct dirent} and @code{struct stat} will change
400 depending on the choice.
402 Beside this difference the @code{glob64} works just like @code{glob} in
403 all aspects.
405 This function is a GNU extension.
406 @end deftypefun
408 @node Flags for Globbing
409 @subsection Flags for Globbing
411 This section describes the flags that you can specify in the
412 @var{flags} argument to @code{glob}.  Choose the flags you want,
413 and combine them with the C bitwise OR operator @code{|}.
415 @vtable @code
416 @comment glob.h
417 @comment POSIX.2
418 @item GLOB_APPEND
419 Append the words from this expansion to the vector of words produced by
420 previous calls to @code{glob}.  This way you can effectively expand
421 several words as if they were concatenated with spaces between them.
423 In order for appending to work, you must not modify the contents of the
424 word vector structure between calls to @code{glob}.  And, if you set
425 @code{GLOB_DOOFFS} in the first call to @code{glob}, you must also
426 set it when you append to the results.
428 Note that the pointer stored in @code{gl_pathv} may no longer be valid
429 after you call @code{glob} the second time, because @code{glob} might
430 have relocated the vector.  So always fetch @code{gl_pathv} from the
431 @code{glob_t} structure after each @code{glob} call; @strong{never} save
432 the pointer across calls.
434 @comment glob.h
435 @comment POSIX.2
436 @item GLOB_DOOFFS
437 Leave blank slots at the beginning of the vector of words.
438 The @code{gl_offs} field says how many slots to leave.
439 The blank slots contain null pointers.
441 @comment glob.h
442 @comment POSIX.2
443 @item GLOB_ERR
444 Give up right away and report an error if there is any difficulty
445 reading the directories that must be read in order to expand @var{pattern}
446 fully.  Such difficulties might include a directory in which you don't
447 have the requisite access.  Normally, @code{glob} tries its best to keep
448 on going despite any errors, reading whatever directories it can.
450 You can exercise even more control than this by specifying an
451 error-handler function @var{errfunc} when you call @code{glob}.  If
452 @var{errfunc} is not a null pointer, then @code{glob} doesn't give up
453 right away when it can't read a directory; instead, it calls
454 @var{errfunc} with two arguments, like this:
456 @smallexample
457 (*@var{errfunc}) (@var{filename}, @var{error-code})
458 @end smallexample
460 @noindent
461 The argument @var{filename} is the name of the directory that
462 @code{glob} couldn't open or couldn't read, and @var{error-code} is the
463 @code{errno} value that was reported to @code{glob}.
465 If the error handler function returns nonzero, then @code{glob} gives up
466 right away.  Otherwise, it continues.
468 @comment glob.h
469 @comment POSIX.2
470 @item GLOB_MARK
471 If the pattern matches the name of a directory, append @samp{/} to the
472 directory's name when returning it.
474 @comment glob.h
475 @comment POSIX.2
476 @item GLOB_NOCHECK
477 If the pattern doesn't match any file names, return the pattern itself
478 as if it were a file name that had been matched.  (Normally, when the
479 pattern doesn't match anything, @code{glob} returns that there were no
480 matches.)
482 @comment glob.h
483 @comment POSIX.2
484 @item GLOB_NOSORT
485 Don't sort the file names; return them in no particular order.
486 (In practice, the order will depend on the order of the entries in
487 the directory.)  The only reason @emph{not} to sort is to save time.
489 @comment glob.h
490 @comment POSIX.2
491 @item GLOB_NOESCAPE
492 Don't treat the @samp{\} character specially in patterns.  Normally,
493 @samp{\} quotes the following character, turning off its special meaning
494 (if any) so that it matches only itself.  When quoting is enabled, the
495 pattern @samp{\?} matches only the string @samp{?}, because the question
496 mark in the pattern acts like an ordinary character.
498 If you use @code{GLOB_NOESCAPE}, then @samp{\} is an ordinary character.
500 @code{glob} does its work by calling the function @code{fnmatch}
501 repeatedly.  It handles the flag @code{GLOB_NOESCAPE} by turning on the
502 @code{FNM_NOESCAPE} flag in calls to @code{fnmatch}.
503 @end vtable
505 @node More Flags for Globbing
506 @subsection More Flags for Globbing
508 Beside the flags described in the last section, the GNU implementation of
509 @code{glob} allows a few more flags which are also defined in the
510 @file{glob.h} file.  Some of the extensions implement functionality
511 which is available in modern shell implementations.
513 @vtable @code
514 @comment glob.h
515 @comment GNU
516 @item GLOB_PERIOD
517 The @code{.} character (period) is treated special.  It cannot be
518 matched by wildcards.  @xref{Wildcard Matching}, @code{FNM_PERIOD}.
520 @comment glob.h
521 @comment GNU
522 @item GLOB_MAGCHAR
523 The @code{GLOB_MAGCHAR} value is not to be given to @code{glob} in the
524 @var{flags} parameter.  Instead, @code{glob} sets this bit in the
525 @var{gl_flags} element of the @var{glob_t} structure provided as the
526 result if the pattern used for matching contains any wildcard character.
528 @comment glob.h
529 @comment GNU
530 @item GLOB_ALTDIRFUNC
531 Instead of the using the using the normal functions for accessing the
532 filesystem the @code{glob} implementation uses the user-supplied
533 functions specified in the structure pointed to by @var{pglob}
534 parameter.  For more information about the functions refer to the
535 sections about directory handling see @ref{Accessing Directories}, and
536 @ref{Reading Attributes}.
538 @comment glob.h
539 @comment GNU
540 @item GLOB_BRACE
541 If this flag is given the handling of braces in the pattern is changed.
542 It is now required that braces appear correctly grouped.  I.e., for each
543 opening brace there must be a closing one.  Braces can be used
544 recursively.  So it is possible to define one brace expression in
545 another one.  It is important to note that the range of each brace
546 expression is completely contained in the outer brace expression (if
547 there is one).
549 The string between the matching braces is separated into single
550 expressions by splitting at @code{,} (comma) characters.  The commas
551 themselves are discarded.  Please note what we said above about recursive
552 brace expressions.  The commas used to separate the subexpressions must
553 be at the same level.  Commas in brace subexpressions are not matched.
554 They are used during expansion of the brace expression of the deeper
555 level.  The example below shows this
557 @smallexample
558 glob ("@{foo/@{,bar,biz@},baz@}", GLOB_BRACE, NULL, &result)
559 @end smallexample
561 @noindent
562 is equivalent to the sequence
564 @smallexample
565 glob ("foo/", GLOB_BRACE, NULL, &result)
566 glob ("foo/bar", GLOB_BRACE|GLOB_APPEND, NULL, &result)
567 glob ("foo/biz", GLOB_BRACE|GLOB_APPEND, NULL, &result)
568 glob ("baz", GLOB_BRACE|GLOB_APPEND, NULL, &result)
569 @end smallexample
571 @noindent
572 if we leave aside error handling.
574 @comment glob.h
575 @comment GNU
576 @item GLOB_NOMAGIC
577 If the pattern contains no wildcard constructs (it is a literal file name),
578 return it as the sole ``matching'' word, even if no file exists by that name.
580 @comment glob.h
581 @comment GNU
582 @item GLOB_TILDE
583 If this flag is used the character @code{~} (tilde) is handled special
584 if it appears at the beginning of the pattern.  Instead of being taken
585 verbatim it is used to represent the home directory of a known user.
587 If @code{~} is the only character in pattern or it is followed by a
588 @code{/} (slash), the home directory of the process owner is
589 substituted.  Using @code{getlogin} and @code{getpwnam} the information
590 is read from the system databases.  As an example take user @code{bart}
591 with his home directory at @file{/home/bart}.  For him a call like
593 @smallexample
594 glob ("~/bin/*", GLOB_TILDE, NULL, &result)
595 @end smallexample
597 @noindent
598 would return the contents of the directory @file{/home/bart/bin}.
599 Instead of referring to the own home directory it is also possible to
600 name the home directory of other users.  To do so one has to append the
601 user name after the tilde character.  So the contents of user
602 @code{homer}'s @file{bin} directory can be retrieved by
604 @smallexample
605 glob ("~homer/bin/*", GLOB_TILDE, NULL, &result)
606 @end smallexample
608 If the user name is not valid or the home directory cannot be determined
609 for some reason the pattern is left untouched and itself used as the
610 result.  I.e., if in the last example @code{home} is not available the
611 tilde expansion yields to @code{"~homer/bin/*"} and @code{glob} is not
612 looking for a directory named @code{~homer}.
614 This functionality is equivalent to what is available in C-shells if the
615 @code{nonomatch} flag is set.
617 @comment glob.h
618 @comment GNU
619 @item GLOB_TILDE_CHECK
620 If this flag is used @code{glob} behaves like as if @code{GLOB_TILDE} is
621 given.  The only difference is that if the user name is not available or
622 the home directory cannot be determined for other reasons this leads to
623 an error.  @code{glob} will return @code{GLOB_NOMATCH} instead of using
624 the pattern itself as the name.
626 This functionality is equivalent to what is available in C-shells if
627 @code{nonomatch} flag is not set.
629 @comment glob.h
630 @comment GNU
631 @item GLOB_ONLYDIR
632 If this flag is used the globbing function takes this as a
633 @strong{hint} that the caller is only interested in directories
634 matching the pattern.  If the information about the type of the file
635 is easily available non-directories will be rejected but no extra
636 work will be done to determine the information for each file.  I.e.,
637 the caller must still be able to filter directories out.
639 This functionality is only available with the GNU @code{glob}
640 implementation.  It is mainly used internally to increase the
641 performance but might be useful for a user as well and therefore is
642 documented here.
643 @end vtable
645 Calling @code{glob} will in most cases allocate resources which are used
646 to represent the result of the function call.  If the same object of
647 type @code{glob_t} is used in multiple call to @code{glob} the resources
648 are freed or reused so that no leaks appear.  But this does not include
649 the time when all @code{glob} calls are done.
651 @comment glob.h
652 @comment POSIX.2
653 @deftypefun void globfree (glob_t *@var{pglob})
654 The @code{globfree} function frees all resources allocated by previous
655 calls to @code{glob} associated with the object pointed to by
656 @var{pglob}.  This function should be called whenever the currently used
657 @code{glob_t} typed object isn't used anymore.
658 @end deftypefun
660 @comment glob.h
661 @comment GNU
662 @deftypefun void globfree64 (glob64_t *@var{pglob})
663 This function is equivalent to @code{globfree} but it frees records of
664 type @code{glob64_t} which were allocated by @code{glob64}.
665 @end deftypefun
668 @node Regular Expressions
669 @section Regular Expression Matching
671 The GNU C library supports two interfaces for matching regular
672 expressions.  One is the standard POSIX.2 interface, and the other is
673 what the GNU system has had for many years.
675 Both interfaces are declared in the header file @file{regex.h}.
676 If you define @w{@code{_POSIX_C_SOURCE}}, then only the POSIX.2
677 functions, structures, and constants are declared.
678 @c !!! we only document the POSIX.2 interface here!!
680 @menu
681 * POSIX Regexp Compilation::    Using @code{regcomp} to prepare to match.
682 * Flags for POSIX Regexps::     Syntax variations for @code{regcomp}.
683 * Matching POSIX Regexps::      Using @code{regexec} to match the compiled
684                                    pattern that you get from @code{regcomp}.
685 * Regexp Subexpressions::       Finding which parts of the string were matched.
686 * Subexpression Complications:: Find points of which parts were matched.
687 * Regexp Cleanup::              Freeing storage; reporting errors.
688 @end menu
690 @node POSIX Regexp Compilation
691 @subsection POSIX Regular Expression Compilation
693 Before you can actually match a regular expression, you must
694 @dfn{compile} it.  This is not true compilation---it produces a special
695 data structure, not machine instructions.  But it is like ordinary
696 compilation in that its purpose is to enable you to ``execute'' the
697 pattern fast.  (@xref{Matching POSIX Regexps}, for how to use the
698 compiled regular expression for matching.)
700 There is a special data type for compiled regular expressions:
702 @comment regex.h
703 @comment POSIX.2
704 @deftp {Data Type} regex_t
705 This type of object holds a compiled regular expression.
706 It is actually a structure.  It has just one field that your programs
707 should look at:
709 @table @code
710 @item re_nsub
711 This field holds the number of parenthetical subexpressions in the
712 regular expression that was compiled.
713 @end table
715 There are several other fields, but we don't describe them here, because
716 only the functions in the library should use them.
717 @end deftp
719 After you create a @code{regex_t} object, you can compile a regular
720 expression into it by calling @code{regcomp}.
722 @comment regex.h
723 @comment POSIX.2
724 @deftypefun int regcomp (regex_t *restrict @var{compiled}, const char *restrict @var{pattern}, int @var{cflags})
725 The function @code{regcomp} ``compiles'' a regular expression into a
726 data structure that you can use with @code{regexec} to match against a
727 string.  The compiled regular expression format is designed for
728 efficient matching.  @code{regcomp} stores it into @code{*@var{compiled}}.
730 It's up to you to allocate an object of type @code{regex_t} and pass its
731 address to @code{regcomp}.
733 The argument @var{cflags} lets you specify various options that control
734 the syntax and semantics of regular expressions.  @xref{Flags for POSIX
735 Regexps}.
737 If you use the flag @code{REG_NOSUB}, then @code{regcomp} omits from
738 the compiled regular expression the information necessary to record
739 how subexpressions actually match.  In this case, you might as well
740 pass @code{0} for the @var{matchptr} and @var{nmatch} arguments when
741 you call @code{regexec}.
743 If you don't use @code{REG_NOSUB}, then the compiled regular expression
744 does have the capacity to record how subexpressions match.  Also,
745 @code{regcomp} tells you how many subexpressions @var{pattern} has, by
746 storing the number in @code{@var{compiled}->re_nsub}.  You can use that
747 value to decide how long an array to allocate to hold information about
748 subexpression matches.
750 @code{regcomp} returns @code{0} if it succeeds in compiling the regular
751 expression; otherwise, it returns a nonzero error code (see the table
752 below).  You can use @code{regerror} to produce an error message string
753 describing the reason for a nonzero value; see @ref{Regexp Cleanup}.
755 @end deftypefun
757 Here are the possible nonzero values that @code{regcomp} can return:
759 @table @code
760 @comment regex.h
761 @comment POSIX.2
762 @item REG_BADBR
763 There was an invalid @samp{\@{@dots{}\@}} construct in the regular
764 expression.  A valid @samp{\@{@dots{}\@}} construct must contain either
765 a single number, or two numbers in increasing order separated by a
766 comma.
768 @comment regex.h
769 @comment POSIX.2
770 @item REG_BADPAT
771 There was a syntax error in the regular expression.
773 @comment regex.h
774 @comment POSIX.2
775 @item REG_BADRPT
776 A repetition operator such as @samp{?} or @samp{*} appeared in a bad
777 position (with no preceding subexpression to act on).
779 @comment regex.h
780 @comment POSIX.2
781 @item REG_ECOLLATE
782 The regular expression referred to an invalid collating element (one not
783 defined in the current locale for string collation).  @xref{Locale
784 Categories}.
786 @comment regex.h
787 @comment POSIX.2
788 @item REG_ECTYPE
789 The regular expression referred to an invalid character class name.
791 @comment regex.h
792 @comment POSIX.2
793 @item REG_EESCAPE
794 The regular expression ended with @samp{\}.
796 @comment regex.h
797 @comment POSIX.2
798 @item REG_ESUBREG
799 There was an invalid number in the @samp{\@var{digit}} construct.
801 @comment regex.h
802 @comment POSIX.2
803 @item REG_EBRACK
804 There were unbalanced square brackets in the regular expression.
806 @comment regex.h
807 @comment POSIX.2
808 @item REG_EPAREN
809 An extended regular expression had unbalanced parentheses,
810 or a basic regular expression had unbalanced @samp{\(} and @samp{\)}.
812 @comment regex.h
813 @comment POSIX.2
814 @item REG_EBRACE
815 The regular expression had unbalanced @samp{\@{} and @samp{\@}}.
817 @comment regex.h
818 @comment POSIX.2
819 @item REG_ERANGE
820 One of the endpoints in a range expression was invalid.
822 @comment regex.h
823 @comment POSIX.2
824 @item REG_ESPACE
825 @code{regcomp} ran out of memory.
826 @end table
828 @node Flags for POSIX Regexps
829 @subsection Flags for POSIX Regular Expressions
831 These are the bit flags that you can use in the @var{cflags} operand when
832 compiling a regular expression with @code{regcomp}.
834 @table @code
835 @comment regex.h
836 @comment POSIX.2
837 @item REG_EXTENDED
838 Treat the pattern as an extended regular expression, rather than as a
839 basic regular expression.
841 @comment regex.h
842 @comment POSIX.2
843 @item REG_ICASE
844 Ignore case when matching letters.
846 @comment regex.h
847 @comment POSIX.2
848 @item REG_NOSUB
849 Don't bother storing the contents of the @var{matches-ptr} array.
851 @comment regex.h
852 @comment POSIX.2
853 @item REG_NEWLINE
854 Treat a newline in @var{string} as dividing @var{string} into multiple
855 lines, so that @samp{$} can match before the newline and @samp{^} can
856 match after.  Also, don't permit @samp{.} to match a newline, and don't
857 permit @samp{[^@dots{}]} to match a newline.
859 Otherwise, newline acts like any other ordinary character.
860 @end table
862 @node Matching POSIX Regexps
863 @subsection Matching a Compiled POSIX Regular Expression
865 Once you have compiled a regular expression, as described in @ref{POSIX
866 Regexp Compilation}, you can match it against strings using
867 @code{regexec}.  A match anywhere inside the string counts as success,
868 unless the regular expression contains anchor characters (@samp{^} or
869 @samp{$}).
871 @comment regex.h
872 @comment POSIX.2
873 @deftypefun int regexec (const regex_t *restrict @var{compiled}, const char *restrict @var{string}, size_t @var{nmatch}, regmatch_t @var{matchptr}[restrict], int @var{eflags})
874 This function tries to match the compiled regular expression
875 @code{*@var{compiled}} against @var{string}.
877 @code{regexec} returns @code{0} if the regular expression matches;
878 otherwise, it returns a nonzero value.  See the table below for
879 what nonzero values mean.  You can use @code{regerror} to produce an
880 error message string describing the reason for a nonzero value;
881 see @ref{Regexp Cleanup}.
883 The argument @var{eflags} is a word of bit flags that enable various
884 options.
886 If you want to get information about what part of @var{string} actually
887 matched the regular expression or its subexpressions, use the arguments
888 @var{matchptr} and @var{nmatch}.  Otherwise, pass @code{0} for
889 @var{nmatch}, and @code{NULL} for @var{matchptr}.  @xref{Regexp
890 Subexpressions}.
891 @end deftypefun
893 You must match the regular expression with the same set of current
894 locales that were in effect when you compiled the regular expression.
896 The function @code{regexec} accepts the following flags in the
897 @var{eflags} argument:
899 @table @code
900 @comment regex.h
901 @comment POSIX.2
902 @item REG_NOTBOL
903 Do not regard the beginning of the specified string as the beginning of
904 a line; more generally, don't make any assumptions about what text might
905 precede it.
907 @comment regex.h
908 @comment POSIX.2
909 @item REG_NOTEOL
910 Do not regard the end of the specified string as the end of a line; more
911 generally, don't make any assumptions about what text might follow it.
912 @end table
914 Here are the possible nonzero values that @code{regexec} can return:
916 @table @code
917 @comment regex.h
918 @comment POSIX.2
919 @item REG_NOMATCH
920 The pattern didn't match the string.  This isn't really an error.
922 @comment regex.h
923 @comment POSIX.2
924 @item REG_ESPACE
925 @code{regexec} ran out of memory.
926 @end table
928 @node Regexp Subexpressions
929 @subsection Match Results with Subexpressions
931 When @code{regexec} matches parenthetical subexpressions of
932 @var{pattern}, it records which parts of @var{string} they match.  It
933 returns that information by storing the offsets into an array whose
934 elements are structures of type @code{regmatch_t}.  The first element of
935 the array (index @code{0}) records the part of the string that matched
936 the entire regular expression.  Each other element of the array records
937 the beginning and end of the part that matched a single parenthetical
938 subexpression.
940 @comment regex.h
941 @comment POSIX.2
942 @deftp {Data Type} regmatch_t
943 This is the data type of the @var{matcharray} array that you pass to
944 @code{regexec}.  It contains two structure fields, as follows:
946 @table @code
947 @item rm_so
948 The offset in @var{string} of the beginning of a substring.  Add this
949 value to @var{string} to get the address of that part.
951 @item rm_eo
952 The offset in @var{string} of the end of the substring.
953 @end table
954 @end deftp
956 @comment regex.h
957 @comment POSIX.2
958 @deftp {Data Type} regoff_t
959 @code{regoff_t} is an alias for another signed integer type.
960 The fields of @code{regmatch_t} have type @code{regoff_t}.
961 @end deftp
963 The @code{regmatch_t} elements correspond to subexpressions
964 positionally; the first element (index @code{1}) records where the first
965 subexpression matched, the second element records the second
966 subexpression, and so on.  The order of the subexpressions is the order
967 in which they begin.
969 When you call @code{regexec}, you specify how long the @var{matchptr}
970 array is, with the @var{nmatch} argument.  This tells @code{regexec} how
971 many elements to store.  If the actual regular expression has more than
972 @var{nmatch} subexpressions, then you won't get offset information about
973 the rest of them.  But this doesn't alter whether the pattern matches a
974 particular string or not.
976 If you don't want @code{regexec} to return any information about where
977 the subexpressions matched, you can either supply @code{0} for
978 @var{nmatch}, or use the flag @code{REG_NOSUB} when you compile the
979 pattern with @code{regcomp}.
981 @node Subexpression Complications
982 @subsection Complications in Subexpression Matching
984 Sometimes a subexpression matches a substring of no characters.  This
985 happens when @samp{f\(o*\)} matches the string @samp{fum}.  (It really
986 matches just the @samp{f}.)  In this case, both of the offsets identify
987 the point in the string where the null substring was found.  In this
988 example, the offsets are both @code{1}.
990 Sometimes the entire regular expression can match without using some of
991 its subexpressions at all---for example, when @samp{ba\(na\)*} matches the
992 string @samp{ba}, the parenthetical subexpression is not used.  When
993 this happens, @code{regexec} stores @code{-1} in both fields of the
994 element for that subexpression.
996 Sometimes matching the entire regular expression can match a particular
997 subexpression more than once---for example, when @samp{ba\(na\)*}
998 matches the string @samp{bananana}, the parenthetical subexpression
999 matches three times.  When this happens, @code{regexec} usually stores
1000 the offsets of the last part of the string that matched the
1001 subexpression.  In the case of @samp{bananana}, these offsets are
1002 @code{6} and @code{8}.
1004 But the last match is not always the one that is chosen.  It's more
1005 accurate to say that the last @emph{opportunity} to match is the one
1006 that takes precedence.  What this means is that when one subexpression
1007 appears within another, then the results reported for the inner
1008 subexpression reflect whatever happened on the last match of the outer
1009 subexpression.  For an example, consider @samp{\(ba\(na\)*s \)*} matching
1010 the string @samp{bananas bas }.  The last time the inner expression
1011 actually matches is near the end of the first word.  But it is
1012 @emph{considered} again in the second word, and fails to match there.
1013 @code{regexec} reports nonuse of the ``na'' subexpression.
1015 Another place where this rule applies is when the regular expression
1016 @smallexample
1017 \(ba\(na\)*s \|nefer\(ti\)* \)*
1018 @end smallexample
1019 @noindent
1020 matches @samp{bananas nefertiti}.  The ``na'' subexpression does match
1021 in the first word, but it doesn't match in the second word because the
1022 other alternative is used there.  Once again, the second repetition of
1023 the outer subexpression overrides the first, and within that second
1024 repetition, the ``na'' subexpression is not used.  So @code{regexec}
1025 reports nonuse of the ``na'' subexpression.
1027 @node Regexp Cleanup
1028 @subsection POSIX Regexp Matching Cleanup
1030 When you are finished using a compiled regular expression, you can
1031 free the storage it uses by calling @code{regfree}.
1033 @comment regex.h
1034 @comment POSIX.2
1035 @deftypefun void regfree (regex_t *@var{compiled})
1036 Calling @code{regfree} frees all the storage that @code{*@var{compiled}}
1037 points to.  This includes various internal fields of the @code{regex_t}
1038 structure that aren't documented in this manual.
1040 @code{regfree} does not free the object @code{*@var{compiled}} itself.
1041 @end deftypefun
1043 You should always free the space in a @code{regex_t} structure with
1044 @code{regfree} before using the structure to compile another regular
1045 expression.
1047 When @code{regcomp} or @code{regexec} reports an error, you can use
1048 the function @code{regerror} to turn it into an error message string.
1050 @comment regex.h
1051 @comment POSIX.2
1052 @deftypefun size_t regerror (int @var{errcode}, const regex_t *restrict @var{compiled}, char *restrict @var{buffer}, size_t @var{length})
1053 This function produces an error message string for the error code
1054 @var{errcode}, and stores the string in @var{length} bytes of memory
1055 starting at @var{buffer}.  For the @var{compiled} argument, supply the
1056 same compiled regular expression structure that @code{regcomp} or
1057 @code{regexec} was working with when it got the error.  Alternatively,
1058 you can supply @code{NULL} for @var{compiled}; you will still get a
1059 meaningful error message, but it might not be as detailed.
1061 If the error message can't fit in @var{length} bytes (including a
1062 terminating null character), then @code{regerror} truncates it.
1063 The string that @code{regerror} stores is always null-terminated
1064 even if it has been truncated.
1066 The return value of @code{regerror} is the minimum length needed to
1067 store the entire error message.  If this is less than @var{length}, then
1068 the error message was not truncated, and you can use it.  Otherwise, you
1069 should call @code{regerror} again with a larger buffer.
1071 Here is a function which uses @code{regerror}, but always dynamically
1072 allocates a buffer for the error message:
1074 @smallexample
1075 char *get_regerror (int errcode, regex_t *compiled)
1077   size_t length = regerror (errcode, compiled, NULL, 0);
1078   char *buffer = xmalloc (length);
1079   (void) regerror (errcode, compiled, buffer, length);
1080   return buffer;
1082 @end smallexample
1083 @end deftypefun
1085 @node Word Expansion
1086 @section Shell-Style Word Expansion
1087 @cindex word expansion
1088 @cindex expansion of shell words
1090 @dfn{Word expansion} means the process of splitting a string into
1091 @dfn{words} and substituting for variables, commands, and wildcards
1092 just as the shell does.
1094 For example, when you write @samp{ls -l foo.c}, this string is split
1095 into three separate words---@samp{ls}, @samp{-l} and @samp{foo.c}.
1096 This is the most basic function of word expansion.
1098 When you write @samp{ls *.c}, this can become many words, because
1099 the word @samp{*.c} can be replaced with any number of file names.
1100 This is called @dfn{wildcard expansion}, and it is also a part of
1101 word expansion.
1103 When you use @samp{echo $PATH} to print your path, you are taking
1104 advantage of @dfn{variable substitution}, which is also part of word
1105 expansion.
1107 Ordinary programs can perform word expansion just like the shell by
1108 calling the library function @code{wordexp}.
1110 @menu
1111 * Expansion Stages::            What word expansion does to a string.
1112 * Calling Wordexp::             How to call @code{wordexp}.
1113 * Flags for Wordexp::           Options you can enable in @code{wordexp}.
1114 * Wordexp Example::             A sample program that does word expansion.
1115 * Tilde Expansion::             Details of how tilde expansion works.
1116 * Variable Substitution::       Different types of variable substitution.
1117 @end menu
1119 @node Expansion Stages
1120 @subsection The Stages of Word Expansion
1122 When word expansion is applied to a sequence of words, it performs the
1123 following transformations in the order shown here:
1125 @enumerate
1126 @item
1127 @cindex tilde expansion
1128 @dfn{Tilde expansion}: Replacement of @samp{~foo} with the name of
1129 the home directory of @samp{foo}.
1131 @item
1132 Next, three different transformations are applied in the same step,
1133 from left to right:
1135 @itemize @bullet
1136 @item
1137 @cindex variable substitution
1138 @cindex substitution of variables and commands
1139 @dfn{Variable substitution}: Environment variables are substituted for
1140 references such as @samp{$foo}.
1142 @item
1143 @cindex command substitution
1144 @dfn{Command substitution}: Constructs such as @w{@samp{`cat foo`}} and
1145 the equivalent @w{@samp{$(cat foo)}} are replaced with the output from
1146 the inner command.
1148 @item
1149 @cindex arithmetic expansion
1150 @dfn{Arithmetic expansion}: Constructs such as @samp{$(($x-1))} are
1151 replaced with the result of the arithmetic computation.
1152 @end itemize
1154 @item
1155 @cindex field splitting
1156 @dfn{Field splitting}: subdivision of the text into @dfn{words}.
1158 @item
1159 @cindex wildcard expansion
1160 @dfn{Wildcard expansion}: The replacement of a construct such as @samp{*.c}
1161 with a list of @samp{.c} file names.  Wildcard expansion applies to an
1162 entire word at a time, and replaces that word with 0 or more file names
1163 that are themselves words.
1165 @item
1166 @cindex quote removal
1167 @cindex removal of quotes
1168 @dfn{Quote removal}: The deletion of string-quotes, now that they have
1169 done their job by inhibiting the above transformations when appropriate.
1170 @end enumerate
1172 For the details of these transformations, and how to write the constructs
1173 that use them, see @w{@cite{The BASH Manual}} (to appear).
1175 @node Calling Wordexp
1176 @subsection Calling @code{wordexp}
1178 All the functions, constants and data types for word expansion are
1179 declared in the header file @file{wordexp.h}.
1181 Word expansion produces a vector of words (strings).  To return this
1182 vector, @code{wordexp} uses a special data type, @code{wordexp_t}, which
1183 is a structure.  You pass @code{wordexp} the address of the structure,
1184 and it fills in the structure's fields to tell you about the results.
1186 @comment wordexp.h
1187 @comment POSIX.2
1188 @deftp {Data Type} {wordexp_t}
1189 This data type holds a pointer to a word vector.  More precisely, it
1190 records both the address of the word vector and its size.
1192 @table @code
1193 @item we_wordc
1194 The number of elements in the vector.
1196 @item we_wordv
1197 The address of the vector.  This field has type @w{@code{char **}}.
1199 @item we_offs
1200 The offset of the first real element of the vector, from its nominal
1201 address in the @code{we_wordv} field.  Unlike the other fields, this
1202 is always an input to @code{wordexp}, rather than an output from it.
1204 If you use a nonzero offset, then that many elements at the beginning of
1205 the vector are left empty.  (The @code{wordexp} function fills them with
1206 null pointers.)
1208 The @code{we_offs} field is meaningful only if you use the
1209 @code{WRDE_DOOFFS} flag.  Otherwise, the offset is always zero
1210 regardless of what is in this field, and the first real element comes at
1211 the beginning of the vector.
1212 @end table
1213 @end deftp
1215 @comment wordexp.h
1216 @comment POSIX.2
1217 @deftypefun int wordexp (const char *@var{words}, wordexp_t *@var{word-vector-ptr}, int @var{flags})
1218 Perform word expansion on the string @var{words}, putting the result in
1219 a newly allocated vector, and store the size and address of this vector
1220 into @code{*@var{word-vector-ptr}}.  The argument @var{flags} is a
1221 combination of bit flags; see @ref{Flags for Wordexp}, for details of
1222 the flags.
1224 You shouldn't use any of the characters @samp{|&;<>} in the string
1225 @var{words} unless they are quoted; likewise for newline.  If you use
1226 these characters unquoted, you will get the @code{WRDE_BADCHAR} error
1227 code.  Don't use parentheses or braces unless they are quoted or part of
1228 a word expansion construct.  If you use quotation characters @samp{'"`},
1229 they should come in pairs that balance.
1231 The results of word expansion are a sequence of words.  The function
1232 @code{wordexp} allocates a string for each resulting word, then
1233 allocates a vector of type @code{char **} to store the addresses of
1234 these strings.  The last element of the vector is a null pointer.
1235 This vector is called the @dfn{word vector}.
1237 To return this vector, @code{wordexp} stores both its address and its
1238 length (number of elements, not counting the terminating null pointer)
1239 into @code{*@var{word-vector-ptr}}.
1241 If @code{wordexp} succeeds, it returns 0.  Otherwise, it returns one
1242 of these error codes:
1244 @table @code
1245 @comment wordexp.h
1246 @comment POSIX.2
1247 @item WRDE_BADCHAR
1248 The input string @var{words} contains an unquoted invalid character such
1249 as @samp{|}.
1251 @comment wordexp.h
1252 @comment POSIX.2
1253 @item WRDE_BADVAL
1254 The input string refers to an undefined shell variable, and you used the flag
1255 @code{WRDE_UNDEF} to forbid such references.
1257 @comment wordexp.h
1258 @comment POSIX.2
1259 @item WRDE_CMDSUB
1260 The input string uses command substitution, and you used the flag
1261 @code{WRDE_NOCMD} to forbid command substitution.
1263 @comment wordexp.h
1264 @comment POSIX.2
1265 @item WRDE_NOSPACE
1266 It was impossible to allocate memory to hold the result.  In this case,
1267 @code{wordexp} can store part of the results---as much as it could
1268 allocate room for.
1270 @comment wordexp.h
1271 @comment POSIX.2
1272 @item WRDE_SYNTAX
1273 There was a syntax error in the input string.  For example, an unmatched
1274 quoting character is a syntax error.
1275 @end table
1276 @end deftypefun
1278 @comment wordexp.h
1279 @comment POSIX.2
1280 @deftypefun void wordfree (wordexp_t *@var{word-vector-ptr})
1281 Free the storage used for the word-strings and vector that
1282 @code{*@var{word-vector-ptr}} points to.  This does not free the
1283 structure @code{*@var{word-vector-ptr}} itself---only the other
1284 data it points to.
1285 @end deftypefun
1287 @node Flags for Wordexp
1288 @subsection Flags for Word Expansion
1290 This section describes the flags that you can specify in the
1291 @var{flags} argument to @code{wordexp}.  Choose the flags you want,
1292 and combine them with the C operator @code{|}.
1294 @table @code
1295 @comment wordexp.h
1296 @comment POSIX.2
1297 @item WRDE_APPEND
1298 Append the words from this expansion to the vector of words produced by
1299 previous calls to @code{wordexp}.  This way you can effectively expand
1300 several words as if they were concatenated with spaces between them.
1302 In order for appending to work, you must not modify the contents of the
1303 word vector structure between calls to @code{wordexp}.  And, if you set
1304 @code{WRDE_DOOFFS} in the first call to @code{wordexp}, you must also
1305 set it when you append to the results.
1307 @comment wordexp.h
1308 @comment POSIX.2
1309 @item WRDE_DOOFFS
1310 Leave blank slots at the beginning of the vector of words.
1311 The @code{we_offs} field says how many slots to leave.
1312 The blank slots contain null pointers.
1314 @comment wordexp.h
1315 @comment POSIX.2
1316 @item WRDE_NOCMD
1317 Don't do command substitution; if the input requests command substitution,
1318 report an error.
1320 @comment wordexp.h
1321 @comment POSIX.2
1322 @item WRDE_REUSE
1323 Reuse a word vector made by a previous call to @code{wordexp}.
1324 Instead of allocating a new vector of words, this call to @code{wordexp}
1325 will use the vector that already exists (making it larger if necessary).
1327 Note that the vector may move, so it is not safe to save an old pointer
1328 and use it again after calling @code{wordexp}.  You must fetch
1329 @code{we_pathv} anew after each call.
1331 @comment wordexp.h
1332 @comment POSIX.2
1333 @item WRDE_SHOWERR
1334 Do show any error messages printed by commands run by command substitution.
1335 More precisely, allow these commands to inherit the standard error output
1336 stream of the current process.  By default, @code{wordexp} gives these
1337 commands a standard error stream that discards all output.
1339 @comment wordexp.h
1340 @comment POSIX.2
1341 @item WRDE_UNDEF
1342 If the input refers to a shell variable that is not defined, report an
1343 error.
1344 @end table
1346 @node Wordexp Example
1347 @subsection @code{wordexp} Example
1349 Here is an example of using @code{wordexp} to expand several strings
1350 and use the results to run a shell command.  It also shows the use of
1351 @code{WRDE_APPEND} to concatenate the expansions and of @code{wordfree}
1352 to free the space allocated by @code{wordexp}.
1354 @smallexample
1356 expand_and_execute (const char *program, const char **options)
1358   wordexp_t result;
1359   pid_t pid
1360   int status, i;
1362   /* @r{Expand the string for the program to run.}  */
1363   switch (wordexp (program, &result, 0))
1364     @{
1365     case 0:                     /* @r{Successful}.  */
1366       break;
1367     case WRDE_NOSPACE:
1368       /* @r{If the error was @code{WRDE_NOSPACE},}
1369          @r{then perhaps part of the result was allocated.}  */
1370       wordfree (&result);
1371     default:                    /* @r{Some other error.}  */
1372       return -1;
1373     @}
1375   /* @r{Expand the strings specified for the arguments.}  */
1376   for (i = 0; options[i] != NULL; i++)
1377     @{
1378       if (wordexp (options[i], &result, WRDE_APPEND))
1379         @{
1380           wordfree (&result);
1381           return -1;
1382         @}
1383     @}
1385   pid = fork ();
1386   if (pid == 0)
1387     @{
1388       /* @r{This is the child process.  Execute the command.} */
1389       execv (result.we_wordv[0], result.we_wordv);
1390       exit (EXIT_FAILURE);
1391     @}
1392   else if (pid < 0)
1393     /* @r{The fork failed.  Report failure.}  */
1394     status = -1;
1395   else
1396     /* @r{This is the parent process.  Wait for the child to complete.}  */
1397     if (waitpid (pid, &status, 0) != pid)
1398       status = -1;
1400   wordfree (&result);
1401   return status;
1403 @end smallexample
1405 @node Tilde Expansion
1406 @subsection Details of Tilde Expansion
1408 It's a standard part of shell syntax that you can use @samp{~} at the
1409 beginning of a file name to stand for your own home directory.  You
1410 can use @samp{~@var{user}} to stand for @var{user}'s home directory.
1412 @dfn{Tilde expansion} is the process of converting these abbreviations
1413 to the directory names that they stand for.
1415 Tilde expansion applies to the @samp{~} plus all following characters up
1416 to whitespace or a slash.  It takes place only at the beginning of a
1417 word, and only if none of the characters to be transformed is quoted in
1418 any way.
1420 Plain @samp{~} uses the value of the environment variable @code{HOME}
1421 as the proper home directory name.  @samp{~} followed by a user name
1422 uses @code{getpwname} to look up that user in the user database, and
1423 uses whatever directory is recorded there.  Thus, @samp{~} followed
1424 by your own name can give different results from plain @samp{~}, if
1425 the value of @code{HOME} is not really your home directory.
1427 @node Variable Substitution
1428 @subsection Details of Variable Substitution
1430 Part of ordinary shell syntax is the use of @samp{$@var{variable}} to
1431 substitute the value of a shell variable into a command.  This is called
1432 @dfn{variable substitution}, and it is one part of doing word expansion.
1434 There are two basic ways you can write a variable reference for
1435 substitution:
1437 @table @code
1438 @item $@{@var{variable}@}
1439 If you write braces around the variable name, then it is completely
1440 unambiguous where the variable name ends.  You can concatenate
1441 additional letters onto the end of the variable value by writing them
1442 immediately after the close brace.  For example, @samp{$@{foo@}s}
1443 expands into @samp{tractors}.
1445 @item $@var{variable}
1446 If you do not put braces around the variable name, then the variable
1447 name consists of all the alphanumeric characters and underscores that
1448 follow the @samp{$}.  The next punctuation character ends the variable
1449 name.  Thus, @samp{$foo-bar} refers to the variable @code{foo} and expands
1450 into @samp{tractor-bar}.
1451 @end table
1453 When you use braces, you can also use various constructs to modify the
1454 value that is substituted, or test it in various ways.
1456 @table @code
1457 @item $@{@var{variable}:-@var{default}@}
1458 Substitute the value of @var{variable}, but if that is empty or
1459 undefined, use @var{default} instead.
1461 @item $@{@var{variable}:=@var{default}@}
1462 Substitute the value of @var{variable}, but if that is empty or
1463 undefined, use @var{default} instead and set the variable to
1464 @var{default}.
1466 @item $@{@var{variable}:?@var{message}@}
1467 If @var{variable} is defined and not empty, substitute its value.
1469 Otherwise, print @var{message} as an error message on the standard error
1470 stream, and consider word expansion a failure.
1472 @c ??? How does wordexp report such an error?
1473 @c WRDE_BADVAL is returned.
1475 @item $@{@var{variable}:+@var{replacement}@}
1476 Substitute @var{replacement}, but only if @var{variable} is defined and
1477 nonempty.  Otherwise, substitute nothing for this construct.
1478 @end table
1480 @table @code
1481 @item $@{#@var{variable}@}
1482 Substitute a numeral which expresses in base ten the number of
1483 characters in the value of @var{variable}.  @samp{$@{#foo@}} stands for
1484 @samp{7}, because @samp{tractor} is seven characters.
1485 @end table
1487 These variants of variable substitution let you remove part of the
1488 variable's value before substituting it.  The @var{prefix} and
1489 @var{suffix} are not mere strings; they are wildcard patterns, just
1490 like the patterns that you use to match multiple file names.  But
1491 in this context, they match against parts of the variable value
1492 rather than against file names.
1494 @table @code
1495 @item $@{@var{variable}%%@var{suffix}@}
1496 Substitute the value of @var{variable}, but first discard from that
1497 variable any portion at the end that matches the pattern @var{suffix}.
1499 If there is more than one alternative for how to match against
1500 @var{suffix}, this construct uses the longest possible match.
1502 Thus, @samp{$@{foo%%r*@}} substitutes @samp{t}, because the largest
1503 match for @samp{r*} at the end of @samp{tractor} is @samp{ractor}.
1505 @item $@{@var{variable}%@var{suffix}@}
1506 Substitute the value of @var{variable}, but first discard from that
1507 variable any portion at the end that matches the pattern @var{suffix}.
1509 If there is more than one alternative for how to match against
1510 @var{suffix}, this construct uses the shortest possible alternative.
1512 Thus, @samp{$@{foo%r*@}} substitutes @samp{tracto}, because the shortest
1513 match for @samp{r*} at the end of @samp{tractor} is just @samp{r}.
1515 @item $@{@var{variable}##@var{prefix}@}
1516 Substitute the value of @var{variable}, but first discard from that
1517 variable any portion at the beginning that matches the pattern @var{prefix}.
1519 If there is more than one alternative for how to match against
1520 @var{prefix}, this construct uses the longest possible match.
1522 Thus, @samp{$@{foo##*t@}} substitutes @samp{or}, because the largest
1523 match for @samp{*t} at the beginning of @samp{tractor} is @samp{tract}.
1525 @item $@{@var{variable}#@var{prefix}@}
1526 Substitute the value of @var{variable}, but first discard from that
1527 variable any portion at the beginning that matches the pattern @var{prefix}.
1529 If there is more than one alternative for how to match against
1530 @var{prefix}, this construct uses the shortest possible alternative.
1532 Thus, @samp{$@{foo#*t@}} substitutes @samp{ractor}, because the shortest
1533 match for @samp{*t} at the beginning of @samp{tractor} is just @samp{t}.
1535 @end table