1 @node Pattern Matching, I/O Overview, Searching and Sorting, Top
2 @chapter Pattern Matching
4 The GNU C Library provides pattern matching facilities for two kinds
5 of patterns: regular expressions and file-name wildcards.
8 * Wildcard Matching:: Matching a wildcard pattern against a single string.
9 * Globbing:: Finding the files that match a wildcard pattern.
10 * Regular Expressions:: Matching regular expressions against strings.
11 * Word Expansion:: Expanding shell variables, nested commands,
12 arithmetic, and wildcards.
13 This is what the shell does with shell commands.
16 @node Wildcard Matching
17 @section Wildcard Matching
20 This section describes how to match a wildcard pattern against a
21 particular string. The result is a yes or no answer: does the
22 string fit the pattern or not. The symbols described here are all
23 declared in @file{fnmatch.h}.
27 @deftypefun int fnmatch (const char *@var{pattern}, const char *@var{string}, int @var{flags})
28 This function tests whether the string @var{string} matches the pattern
29 @var{pattern}. It returns @code{0} if they do match; otherwise, it
30 returns the nonzero value @code{FNM_NOMATCH}. The arguments
31 @var{pattern} and @var{string} are both strings.
33 The argument @var{flags} is a combination of flag bits that alter the
34 details of matching. See below for a list of the defined flags.
36 In the GNU C Library, @code{fnmatch} cannot experience an ``error''---it
37 always returns an answer for whether the match succeeds. However, other
38 implementations of @code{fnmatch} might sometimes report ``errors''.
39 They would do so by returning nonzero values that are not equal to
43 These are the available flags for the @var{flags} argument:
49 Treat the @samp{/} character specially, for matching file names. If
50 this flag is set, wildcard constructs in @var{pattern} cannot match
51 @samp{/} in @var{string}. Thus, the only way to match @samp{/} is with
52 an explicit @samp{/} in @var{pattern}.
57 This is an alias for @code{FNM_FILE_NAME}; it comes from POSIX.2. We
58 don't recommend this name because we don't use the term ``pathname'' for
64 Treat the @samp{.} character specially if it appears at the beginning of
65 @var{string}. If this flag is set, wildcard constructs in @var{pattern}
66 cannot match @samp{.} as the first character of @var{string}.
68 If you set both @code{FNM_PERIOD} and @code{FNM_FILE_NAME}, then the
69 special treatment applies to @samp{.} following @samp{/} as well as
70 to @samp{.} at the beginning of @var{string}.
75 Don't treat the @samp{\} character specially in patterns. Normally,
76 @samp{\} quotes the following character, turning off its special meaning
77 (if any) so that it matches only itself. When quoting is enabled, the
78 pattern @samp{\?} matches only the string @samp{?}, because the question
79 mark in the pattern acts like an ordinary character.
81 If you use @code{FNM_NOESCAPE}, then @samp{\} is an ordinary character.
86 Ignore a trailing sequence of characters starting with a @samp{/} in
87 @var{string}; that is to say, test whether @var{string} starts with a
88 directory name that @var{pattern} matches.
90 If this flag is set, either @samp{foo*} or @samp{foobar} as a pattern
91 would match the string @samp{foobar/frobozz}.
98 The archetypal use of wildcards is for matching against the files in a
99 directory, and making a list of all the matches. This is called
102 You could do this using @code{fnmatch}, by reading the directory entries
103 one by one and testing each one with @code{fnmatch}. But that would be
104 slow (and complex, since you would have to handle subdirectories by
107 The library provides a function @code{glob} to make this particular use
108 of wildcards convenient. @code{glob} and the other symbols in this
109 section are declared in @file{glob.h}.
112 * Calling Glob:: Basic use of @code{glob}.
113 * Flags for Globbing:: Flags that enable various options in @code{glob}.
117 @subsection Calling @code{glob}
119 The result of globbing is a vector of file names (strings). To return
120 this vector, @code{glob} uses a special data type, @code{glob_t}, which
121 is a structure. You pass @code{glob} the address of the structure, and
122 it fills in the structure's fields to tell you about the results.
126 @deftp {Data Type} glob_t
127 This data type holds a pointer to a word vector. More precisely, it
128 records both the address of the word vector and its size.
132 The number of elements in the vector.
135 The address of the vector. This field has type @code{char **}.
138 The offset of the first real element of the vector, from its nominal
139 address in the @code{gl_pathv} field. Unlike the other fields, this
140 is always an input to @code{glob}, rather than an output from it.
142 If you use a nonzero offset, then that many elements at the beginning of
143 the vector are left empty. (The @code{glob} function fills them with
146 The @code{gl_offs} field is meaningful only if you use the
147 @code{GLOB_DOOFFS} flag. Otherwise, the offset is always zero
148 regardless of what is in this field, and the first real element comes at
149 the beginning of the vector.
155 @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})
156 The function @code{glob} does globbing using the pattern @var{pattern}
157 in the current directory. It puts the result in a newly allocated
158 vector, and stores the size and address of this vector into
159 @code{*@var{vector-ptr}}. The argument @var{flags} is a combination of
160 bit flags; see @ref{Flags for Globbing}, for details of the flags.
162 The result of globbing is a sequence of file names. The function
163 @code{glob} allocates a string for each resulting word, then
164 allocates a vector of type @code{char **} to store the addresses of
165 these strings. The last element of the vector is a null pointer.
166 This vector is called the @dfn{word vector}.
168 To return this vector, @code{glob} stores both its address and its
169 length (number of elements, not counting the terminating null pointer)
170 into @code{*@var{vector-ptr}}.
172 Normally, @code{glob} sorts the file names alphabetically before
173 returning them. You can turn this off with the flag @code{GLOB_NOSORT}
174 if you want to get the information as fast as possible. Usually it's
175 a good idea to let @code{glob} sort them---if you process the files in
176 alphabetical order, the users will have a feel for the rate of progress
177 that your application is making.
179 If @code{glob} succeeds, it returns 0. Otherwise, it returns one
180 of these error codes:
186 There was an error opening a directory, and you used the flag
187 @code{GLOB_ERR} or your specified @var{errfunc} returned a nonzero
193 The pattern didn't match any existing files. If you use the
194 @code{GLOB_NOCHECK} flag, then you never get this error code, because
195 that flag tells @code{glob} to @emph{pretend} that the pattern matched
201 It was impossible to allocate memory to hold the result.
204 In the event of an error, @code{glob} stores information in
205 @code{*@var{vector-ptr}} about all the matches it has found so far.
208 @node Flags for Globbing
209 @subsection Flags for Globbing
211 This section describes the flags that you can specify in the
212 @var{flags} argument to @code{glob}. Choose the flags you want,
213 and combine them with the C operator @code{|}.
219 Append the words from this expansion to the vector of words produced by
220 previous calls to @code{glob}. This way you can effectively expand
221 several words as if they were concatenated with spaces between them.
223 In order for appending to work, you must not modify the contents of the
224 word vector structure between calls to @code{glob}. And, if you set
225 @code{GLOB_DOOFFS} in the first call to @code{glob}, you must also
226 set it when you append to the results.
231 Leave blank slots at the beginning of the vector of words.
232 The @code{gl_offs} field says how many slots to leave.
233 The blank slots contain null pointers.
238 Give up right away and report an error if there is any difficulty
239 reading the directories that must be read in order to expand @var{pattern}
240 fully. Such difficulties might include a directory in which you don't
241 have the requisite access. Normally, @code{glob} tries its best to keep
242 on going despite any errors, reading whatever directories it can.
244 You can exercise even more control than this by specifying an error-handler
245 function @var{errfunc} when you call @code{glob}. If @var{errfunc} is
246 nonzero, then @code{glob} doesn't give up right away when it can't read
247 a directory; instead, it calls @var{errfunc} with two arguments, like
251 (*@var{errfunc}) (@var{filename}, @var{error-code})
255 The argument @var{filename} is the name of the directory that
256 @code{glob} couldn't open or couldn't read, and @var{error-code} is the
257 @code{errno} value that was reported to @code{glob}.
259 If the error handler function returns nonzero, then @code{glob} gives up
260 right away. Otherwise, it continues.
265 If the pattern matches the name of a directory, append @samp{/} to the
266 directory's name when returning it.
271 If the pattern doesn't match any file names, return the pattern itself
272 as if it were a file name that had been matched. (Normally, when the
273 pattern doesn't match anything, @code{glob} returns that there were no
279 Don't sort the file names; return them in no particular order.
280 (In practice, the order will depend on the order of the entries in
281 the directory.) The only reason @emph{not} to sort is to save time.
286 Don't treat the @samp{\} character specially in patterns. Normally,
287 @samp{\} quotes the following character, turning off its special meaning
288 (if any) so that it matches only itself. When quoting is enabled, the
289 pattern @samp{\?} matches only the string @samp{?}, because the question
290 mark in the pattern acts like an ordinary character.
292 If you use @code{GLOB_NOESCAPE}, then @samp{\} is an ordinary character.
294 @code{glob} does its work by calling the function @code{fnmatch}
295 repeatedly. It handles the flag @code{GLOB_NOESCAPE} by turning on the
296 @code{FNM_NOESCAPE} flag in calls to @code{fnmatch}.
299 @node Regular Expressions
300 @section Regular Expression Matching
302 The GNU C library supports two interfaces for matching regular
303 expressions. One is the standard POSIX.2 interface, and the other is
304 what the GNU system has had for many years.
306 Both interfaces are declared in the header file @file{regex.h}.
307 If you define @code{_GNU_SOURCE}, then the GNU functions, structures
308 and constants are declared. Otherwise, only the POSIX names are
310 @c !!! wrong-- default is GNU
313 * POSIX Regexp Compilation:: Using @code{regcomp} to prepare to match.
314 * Flags for POSIX Regexps:: Syntax variations for @code{regcomp}.
315 * Matching POSIX Regexps:: Using @code{regexec} to match the compiled
316 pattern that you get from @code{regcomp}.
317 * Regexp Subexpressions:: Finding which parts of the string were matched.
318 * Subexpression Complications:: Find points of which parts were matched.
319 * Regexp Cleanup:: Freeing storage; reporting errors.
322 @node POSIX Regexp Compilation
323 @subsection POSIX Regular Expression Compilation
325 Before you can actually match a regular expression, you must
326 @dfn{compile} it. This is not true compilation---it produces a special
327 data structure, not machine instructions. But it is like ordinary
328 compilation in that its purpose is to enable you to ``execute'' the
329 pattern fast. (@xref{Matching POSIX Regexps}, for how to use the
330 compiled regular expression for matching.)
332 There is a special data type for compiled regular expressions:
336 @deftp {Data Type} regex_t
337 This type of object holds a compiled regular expression.
338 It is actually a structure. It has just one field that your programs
343 This field holds the number of parenthetical subexpressions in the
344 regular expression that was compiled.
347 There are several other fields, but we don't describe them here, because
348 only the functions in the library should use them.
351 After you create a @code{regex_t} object, you can compile a regular
352 expression into it by calling @code{regcomp}.
356 @deftypefun int regcomp (regex_t *@var{compiled}, const char *@var{pattern}, int @var{cflags})
357 The function @code{regcomp} ``compiles'' a regular expression into a
358 data structure that you can use with @code{regexec} to match against a
359 string. The compiled regular expression format is designed for
360 efficient matching. @code{regcomp} stores it into @code{*@var{compiled}}.
362 It's up to you to allocate an object of type @code{regex_t} and pass its
363 address to @code{regcomp}.
365 The argument @var{cflags} lets you specify various options that control
366 the syntax and semantics of regular expressions. @xref{Flags for POSIX
369 If you use the flag @code{REG_NOSUB}, then @code{regcomp} omits from
370 the compiled regular expression the information necessary to record
371 how subexpressions actually match. In this case, you might as well
372 pass @code{0} for the @var{matchptr} and @var{nmatch} arguments when
373 you call @code{regexec}.
375 If you don't use @code{REG_NOSUB}, then the compiled regular expression
376 does have the capacity to record how subexpressions match. Also,
377 @code{regcomp} tells you how many subexpressions @var{pattern} has, by
378 storing the number in @code{@var{compiled}->re_nsub}. You can use that
379 value to decide how long an array to allocate to hold information about
380 subexpression matches.
382 @code{regcomp} returns @code{0} if it succeeds in compiling the regular
383 expression; otherwise, it returns a nonzero error code (see the table
384 below). You can use @code{regerror} to produce an error message string
385 describing the reason for a nonzero value; see @ref{Regexp Cleanup}.
389 Here are the possible nonzero values that @code{regcomp} can return:
395 There was an invalid @samp{\@{@dots{}\@}} construct in the regular
396 expression. A valid @samp{\@{@dots{}\@}} construct must contain either
397 a single number, or two numbers in increasing order separated by a
403 There was a syntax error in the regular expression.
408 A repetition operator such as @samp{?} or @samp{*} appeared in a bad
409 position (with no preceding subexpression to act on).
414 The regular expression referred to an invalid collating element (one not
415 defined in the current locale for string collation). @xref{Locale
421 The regular expression referred to an invalid character class name.
426 The regular expression ended with @samp{\}.
431 There was an invalid number in the @samp{\@var{digit}} construct.
436 There were unbalanced square brackets in the regular expression.
441 An extended regular expression had unbalanced parentheses,
442 or a basic regular expression had unbalanced @samp{\(} and @samp{\)}.
447 The regular expression had unbalanced @samp{\@{} and @samp{\@}}.
452 One of the endpoints in a range expression was invalid.
457 @code{regcomp} or @code{regexec} ran out of memory.
460 @node Flags for POSIX Regexps
461 @subsection Flags for POSIX Regular Expressions
463 These are the bit flags that you can use in the @var{cflags} operand when
464 compiling a regular expression with @code{regcomp}.
470 Treat the pattern as an extended regular expression, rather than as a
471 basic regular expression.
476 Ignore case when matching letters.
481 Don't bother storing the contents of the @var{matches_ptr} array.
486 Treat a newline in @var{string} as dividing @var{string} into multiple
487 lines, so that @samp{$} can match before the newline and @samp{^} can
488 match after. Also, don't permit @samp{.} to match a newline, and don't
489 permit @samp{[^@dots{}]} to match a newline.
491 Otherwise, newline acts like any other ordinary character.
494 @node Matching POSIX Regexps
495 @subsection Matching a Compiled POSIX Regular Expression
497 Once you have compiled a regular expression, as described in @ref{POSIX
498 Regexp Compilation}, you can match it against strings using
499 @code{regexec}. A match anywhere inside the string counts as success,
500 unless the regular expression contains anchor characters (@samp{^} or
505 @deftypefun int regexec (regex_t *@var{compiled}, char *@var{string}, size_t @var{nmatch}, regmatch_t @var{matchptr} @t{[]}, int @var{eflags})
506 This function tries to match the compiled regular expression
507 @code{*@var{compiled}} against @var{string}.
509 @code{regexec} returns @code{0} if the regular expression matches;
510 otherwise, it returns a nonzero value. See the table below for
511 what nonzero values mean. You can use @code{regerror} to produce an
512 error message string describing the reason for a nonzero value;
513 see @ref{Regexp Cleanup}.
515 The argument @var{eflags} is a word of bit flags that enable various
518 If you want to get information about what part of @var{string} actually
519 matched the regular expression or its subexpressions, use the arguments
520 @var{matchptr} and @var{nmatch}. Otherwise, pass @code{0} for
521 @var{nmatch}, and @code{NULL} for @var{matchptr}. @xref{Regexp
525 You must match the regular expression with the same set of current
526 locales that were in effect when you compiled the regular expression.
528 The function @code{regexec} accepts the following flags in the
529 @var{eflags} argument:
535 Do not regard the beginning of the specified string as the beginning of
536 a line; more generally, don't make any assumptions about what text might
542 Do not regard the end of the specified string as the end of a line; more
543 generally, don't make any assumptions about what text might follow it.
546 Here are the possible nonzero values that @code{regexec} can return:
552 The pattern didn't match the string. This isn't really an error.
557 @code{regcomp} or @code{regexec} ran out of memory.
560 @node Regexp Subexpressions
561 @c !!! I think this title is awkward -rm
562 @subsection Subexpressions Match Results
564 When @code{regexec} matches parenthetical subexpressions of
565 @var{pattern}, it records which parts of @var{string} they match. It
566 returns that information by storing the offsets into an array whose
567 elements are structures of type @code{regmatch_t}. The first element of
568 the array records the part of the string that matched the entire regular
569 expression. Each other element of the array records the beginning and
570 end of the part that matched a single parenthetical subexpression.
571 @c !!! in this paragraph, [0] is called "first"; see below
575 @deftp {Data Type} regmatch_t
576 This is the data type of the @var{matcharray} array that you pass to
577 @code{regexec}. It containes two structure fields, as follows:
581 The offset in @var{string} of the beginning of a substring. Add this
582 value to @var{string} to get the address of that part.
585 The offset in @var{string} of the end of the substring.
591 @deftp {Data Type} regoff_t
592 @code{regoff_t} is an alias for another signed integer type.
593 The fields of @code{regmatch_t} have type @code{regoff_t}.
596 The @code{regmatch_t} elements correspond to subexpressions
597 positionally; the first element records where the first subexpression
598 matched, the second element records the second subexpression, and so on.
599 The order of the subexpressions is the order in which they begin.
600 @c !!! here [1] is called "first"; see above
602 When you call @code{regexec}, you specify how long the @var{matchptr}
603 array is, with the @var{nmatch} argument. This tells @code{regexec} how
604 many elements to store. If the actual regular expression has more than
605 @var{nmatch} subexpressions, then you won't get offset information about
606 the rest of them. But this doesn't alter whether the pattern matches a
607 particular string or not.
609 If you don't want @code{regexec} to return any information about where
610 the subexpressions matched, you can either supply @code{0} for
611 @var{nmatch}, or use the flag @code{REG_NOSUB} when you compile the
612 pattern with @code{regcomp}.
614 @node Subexpression Complications
615 @subsection Complications in Subexpression Matching
617 Sometimes a subexpression matches a substring of no characters. This
618 happens when @samp{f\(o*\)} matches the string @samp{fum}. (It really
619 matches just the @samp{f}.) In this case, both of the offsets identify
620 the point in the string where the null substring was found. In this
621 example, the offsets are both @code{1}.
623 Sometimes the entire regular expression can match without using some of
624 its subexpressions at all---for example, when @samp{ba\(na\)*} matches the
625 string @samp{ba}, the parenthetical subexpression is not used. When
626 this happens, @code{regexec} stores @code{-1} in both fields of the
627 element for that subexpression.
629 Sometimes matching the entire regular expression can match a particular
630 subexpression more than once---for example, when @samp{ba\(na\)*}
631 matches the string @samp{bananana}, the parenthetical subexpression
632 matches three times. When this happens, @code{regexec} usually stores
633 the offsets of the last part of the string that matched the
634 subexpression. In the case of @samp{bananana}, these offsets are
635 @code{6} and @code{8}.
637 But the last match is not always the one that is chosen. It's more
638 accurate to say that the last @emph{opportunity} to match is the one
639 that takes precedence. What this means is that when one subexpression
640 appears within another, then the results reported for the inner
641 subexpression reflect whatever happened on the last match of the outer
642 subexpression. For an example, consider @samp{\(ba\(na\)*s \)} matching
643 the string @samp{bananas bas }. The last time the inner expression
644 actually matches is near the end of the first word. But it is
645 @emph{considered} again in the second word, and fails to match there.
646 @code{regexec} reports nonuse of the ``na'' subexpression.
648 Another place where this rule applies is when @samp{\(ba\(na\)*s
649 \|nefer\(ti\)* \)*} matches @samp{bananas nefertiti}. The ``na''
650 subexpression does match in the first word, but it doesn't match in the
651 second word because the other alternative is used there. Once again,
652 the second repetition of the outer subexpression overrides the first,
653 and within that second repetition, the ``na'' subexpression is not used.
654 So @code{regexec} reports nonuse of the ``na'' subexpression.
657 @subsection POSIX Regexp Matching Cleanup
659 When you are finished using a compiled regular expression, you can
660 free the storage it uses by calling @code{regfree}.
664 @deftypefun void regfree (regex_t *@var{compiled})
665 Calling @code{regfree} frees all the storage that @code{*@var{compiled}}
666 points to. This includes various internal fields of the @code{regex_t}
667 structure that aren't documented in this manual.
669 @code{regfree} does not free the object @code{*@var{compiled}} itself.
672 You should always free the space in a @code{regex_t} structure with
673 @code{regfree} before using the structure to compile another regular
676 When @code{regcomp} or @code{regexec} reports an error, you can use
677 the function @code{regerror} to turn it into an error message string.
681 @deftypefun size_t regerror (int @var{errcode}, regex_t *@var{compiled}, char *@var{buffer}, size_t @var{length})
682 This function produces an error message string for the error code
683 @var{errcode}, and stores the string in @var{length} bytes of memory
684 starting at @var{buffer}. For the @var{compiled} argument, supply the
685 same compiled regular expression structure that @code{regcomp} or
686 @code{regexec} was working with when it got the error. Alternatively,
687 you can supply @code{NULL} for @var{compiled}; you will still get a
688 meaningful error message, but it might not be as detailed.
690 If the error message can't fit in @var{length} bytes (including a
691 terminating null character), then @code{regerror} truncates it.
692 The string that @code{regerror} stores is always null-terminated
693 even if it has been truncated.
695 The return value of @code{regerror} is the minimum length needed to
696 store the entire error message. If this is less than @var{length}, then
697 the error message was not truncated, and you can use it. Otherwise, you
698 should call @code{regerror} again with a larger buffer.
700 @c !!! i wrote this example of how to do it right (i think) -- intro it. -rm
702 char *get_regerror (int errcode, regex_t *compiled)
704 size_t length = regerror (errcode, compiled, NULL, 0);
705 char *buffer = xmalloc (length);
706 (void) regerror (errcode, compiled, buffer, length);
712 @c !!!! this is not actually in the library....
714 @section Shell-Style Word Expansion
715 @cindex word expansion
716 @cindex expansion of shell words
718 @dfn{Word expansion} means the process of splitting a string into
719 @dfn{words} and substituting for variables, commands, and wildcards
720 just as the shell does.
722 For example, when you write @samp{ls -l foo.c}, this string is split
723 into three separate words---@samp{ls}, @samp{-l} and @samp{foo.c}.
724 This is the most basic function of word expansion.
726 When you write @samp{ls *.c}, this can become many words, because
727 the word @samp{*.c} can be replaced with any number of file names.
728 This is called @dfn{wildcard expansion}, and it is also a part of
731 When you use @samp{echo $PATH} to print your path, you are taking
732 advantage of @dfn{variable substitution}, which is also part of word
735 Ordinary programs can perform word expansion just like the shell by
736 calling the library function @code{wordexp}.
739 * Expansion Stages:: What word expansion does to a string.
740 * Calling Wordexp:: How to call @code{wordexp}.
741 * Flags for Wordexp:: Options you can enable in @code{wordexp}.
742 * Wordexp Example:: A sample program that does word expansion.
745 @node Expansion Stages
746 @subsection The Stages of Word Expansion
748 When word expansion is applied to a sequence of words, it performs the
749 following transformations in the order shown here:
753 @cindex tilde expansion
754 @dfn{Tilde expansion}: Replacement of @samp{~foo} with the name of
755 the home directory of @samp{foo}.
758 Next, three different transformations are applied in the same step,
763 @cindex variable substitution
764 @cindex substitution of variables and commands
765 @dfn{Variable substitution}: The substitution of environment variables
766 for references such as @samp{$foo}.
769 @cindex command substitution
770 @dfn{Command substitution}: Replacement of constructs such as
771 @samp{`cat foo`} or @samp{$(cat foo)} with the output from the inner
775 @cindex arithmetic expansion
776 @dfn{Arithmetic expansion}: Replacement of constructs such as
777 @samp{$(($x-1))} with the result of the arithmetic computation.
781 @cindex field splitting
782 @dfn{Field splitting}: subdivision of the text into @dfn{words}.
785 @cindex wildcard expansion
786 @dfn{Wildcard expansion}: The replacement of a construct such as @samp{*.c}
787 with a list of @samp{.c} file names. Wildcard expansion applies to an
788 entire word at a time, and replaces that word with 0 or more file names
789 that are themselves words.
792 @cindex quote removal
793 @cindex removal of quotes
794 @dfn{Quote removal}: The deletion of string-quotes, now that they have
795 done their job by inhibiting the above transformations when appropriate.
798 For the details of these transformations, and how to write the constructs
799 that use them, see @w{@cite{The BASH Manual}} (to appear).
801 @node Calling Wordexp
802 @subsection Calling @code{wordexp}
804 All the functions, constants and data types for word expansion are
805 declared in the header file @file{wordexp.h}.
807 Word expansion produces a vector of words (strings). To return this
808 vector, @code{wordexp} uses a special data type, @code{wordexp_t}, which
809 is a structure. You pass @code{wordexp} the address of the structure,
810 and it fills in the structure's fields to tell you about the results.
814 @deftp {Data Type} {wordexp_t}
815 This data type holds a pointer to a word vector. More precisely, it
816 records both the address of the word vector and its size.
820 The number of elements in the vector.
823 The address of the vector. This field has type @code{char **}.
826 The offset of the first real element of the vector, from its nominal
827 address in the @code{we_wordv} field. Unlike the other fields, this
828 is always an input to @code{wordexp}, rather than an output from it.
830 If you use a nonzero offset, then that many elements at the beginning of
831 the vector are left empty. (The @code{wordexp} function fills them with
834 The @code{we_offs} field is meaningful only if you use the
835 @code{WRDE_DOOFFS} flag. Otherwise, the offset is always zero
836 regardless of what is in this field, and the first real element comes at
837 the beginning of the vector.
843 @deftypefun int wordexp (const char *@var{words}, wordexp_t *@var{word-vector-ptr}, int @var{flags})
844 Perform word expansion on the string @var{words}, putting the result in
845 a newly allocated vector, and store the size and address of this vector
846 into @code{*@var{word-vector-ptr}}. The argument @var{flags} is a
847 combination of bit flags; see @ref{Flags for Wordexp}, for details of
850 You shouldn't use any of the characters @samp{|&;<>} in the string
851 @var{words} unless they are quoted; likewise for newline. If you use
852 these characters unquoted, you will get the @code{WRDE_BADCHAR} error
853 code. Don't use parentheses or braces unless they are quoted or part of
854 a word expansion construct. If you use quotation characters @samp{'"`},
855 they should come in pairs that balance.
857 The results of word expansion are a sequence of words. The function
858 @code{wordexp} allocates a string for each resulting word, then
859 allocates a vector of type @code{char **} to store the addresses of
860 these strings. The last element of the vector is a null pointer.
861 This vector is called the @dfn{word vector}.
863 To return this vector, @code{wordexp} stores both its address and its
864 length (number of elements, not counting the terminating null pointer)
865 into @code{*@var{word-vector-ptr}}.
867 If @code{wordexp} succeeds, it returns 0. Otherwise, it returns one
868 of these error codes:
874 The input string @var{words} contains an unquoted invalid character such
880 The input string refers to an undefined shell variable, and you used the flag
881 @code{WRDE_UNDEF} to forbid such references.
886 The input string uses command substitution, and you used the flag
887 @code{WRDE_NOCMD} to forbid command substitution.
892 It was impossible to allocate memory to hold the result. In this case,
893 @code{wordexp} can store part of the results---as much as it could
899 There was a syntax error in the input string. For example, an unmatched
900 quoting character is a syntax error.
906 @deftypefun void wordfree (wordexp_t *@var{word-vector-ptr})
907 Free the storage used for the word-strings and vector that
908 @code{*@var{word-vector-ptr}} points to. This does not free the
909 structure @code{*@var{word-vector-ptr}} itself---only the other
913 @node Flags for Wordexp
914 @subsection Flags for Word Expansion
916 This section describes the flags that you can specify in the
917 @var{flags} argument to @code{wordexp}. Choose the flags you want,
918 and combine them with the C operator @code{|}.
924 Append the words from this expansion to the vector of words produced by
925 previous calls to @code{wordexp}. This way you can effectively expand
926 several words as if they were concatenated with spaces between them.
928 In order for appending to work, you must not modify the contents of the
929 word vector structure between calls to @code{wordexp}. And, if you set
930 @code{WRDE_DOOFFS} in the first call to @code{wordexp}, you must also
931 set it when you append to the results.
936 Leave blank slots at the beginning of the vector of words.
937 The @code{we_offs} field says how many slots to leave.
938 The blank slots contain null pointers.
943 Don't do command substitution; if the input requests command substitution,
949 Reuse a word vector made by a previous call to @code{wordexp}.
950 Instead of allocating a new vector of words, this call to @code{wordexp}
951 will use the vector that already exists (making it larger if necessary).
956 Do show any error messages printed by commands run by command substitution.
957 More precisely, allow these commands to inherit the standard error output
958 stream of the current process. By default, @code{wordexp} gives these
959 commands a standard error stream that discards all output.
964 If the input refers to a shell variable that is not defined, report an
968 @node Wordexp Example
969 @subsection @code{wordexp} Example
971 Here is an example of using @code{wordexp} to expand several strings
972 and use the results to run a shell command. It also shows the use of
973 @code{WRDE_APPEND} to concatenate the expansions and of @code{wordfree}
974 to free the space allocated by @code{wordexp}.
978 expand_and_execute (const char *program, const char *options)
984 /* @r{Expand the string for the program to run.} */
985 switch (wordexp (program, &result, 0))
987 case 0: /* @r{Successful}. */
990 /* @r{If the error was @code{WRDE_NOSPACE},}
991 @r{then perhaps part of the result was allocated.} */
993 default: /* @r{Some other error.} */
997 /* @r{Expand the strings specified for the arguments.} */
998 for (i = 0; args[i]; i++)
1000 if (wordexp (options, &result, WRDE_APPEND))
1010 /* @r{This is the child process. Execute the command.} */
1011 execv (result.we_wordv[0], result.we_wordv);
1012 exit (EXIT_FAILURE);
1015 /* @r{The fork failed. Report failure.} */
1018 /* @r{This is the parent process. Wait for the child to complete.} */
1019 if (waitpid (pid, &status, 0) != pid)
1027 In practice, since @code{wordexp} is executed by running a subshell, it
1028 would be faster to do this by concatenating the strings with spaces
1029 between them and running that as a shell command using @samp{sh -c}.
1031 @c No sense finishing this for here.
1033 @node Tilde Expansion
1034 @subsection Details of Tilde Expansion
1036 It's a standard part of shell syntax that you can use @samp{~} at the
1037 beginning of a file name to stand for your own home directory. You
1038 can use @samp{~@var{user}} to stand for @var{user}'s home directory.
1040 @dfn{Tilde expansion} is the process of converting these abbreviations
1041 to the directory names that they stand for.
1043 Tilde expansion applies to the @samp{~} plus all following characters up
1044 to whitespace or a slash. It takes place only at the beginning of a
1045 word, and only if none of the characters to be transformed is quoted in
1048 Plain @samp{~} uses the value of the environment variable @code{HOME}
1049 as the proper home directory name. @samp{~} followed by a user name
1050 uses @code{getpwname} to look up that user in the user database, and
1051 uses whatever directory is recorded there. Thus, @samp{~} followed
1052 by your own name can give different results from plain @samp{~}, if
1053 the value of @code{HOME} is not really your home directory.
1055 @node Variable Substitution
1056 @subsection Details of Variable Substitution
1058 Part of ordinary shell syntax is the use of @samp{$@var{variable}} to
1059 substitute the value of a shell variable into a command. This is called
1060 @dfn{variable substitution}, and it is one part of doing word expansion.
1062 There are two basic ways you can write a variable reference for
1066 @item $@{@var{variable}@}
1067 If you write braces around the variable name, then it is completely
1068 unambiguous where the variable name ends. You can concatenate
1069 additional letters onto the end of the variable value by writing them
1070 immediately after the close brace. For example, @samp{$@{foo@}s}
1071 expands into @samp{tractors}.
1073 @item $@var{variable}
1074 If you do not put braces around the variable name, then the variable
1075 name consists of all the alphanumeric characters and underscores that
1076 follow the @samp{$}. The next punctuation character ends the variable
1077 name. Thus, @samp{$foo-bar} refers to the variable @code{foo} and expands
1078 into @samp{tractor-bar}.
1081 When you use braces, you can also use various constructs to modify the
1082 value that is substituted, or test it in various ways.
1085 @item $@{@var{variable}:-@var{default}@}
1086 Substitute the value of @var{variable}, but if that is empty or
1087 undefined, use @var{default} instead.
1089 @item $@{@var{variable}:=@var{default}@}
1090 Substitute the value of @var{variable}, but if that is empty or
1091 undefined, use @var{default} instead and set the variable to
1094 @item $@{@var{variable}:?@var{message}@}
1095 If @var{variable} is defined and not empty, substitute its value.
1097 Otherwise, print @var{message} as an error message on the standard error
1098 stream, and consider word expansion a failure.
1100 @c ??? How does wordexp report such an error?
1102 @item $@{@var{variable}:+@var{replacement}@}
1103 Substitute @var{replacement}, but only if @var{variable} is defined and
1104 nonempty. Otherwise, substitute nothing for this construct.
1108 @item $@{#@var{variable}@}
1109 Substitute a numeral which expresses in base ten the number of
1110 characters in the value of @var{variable}. @samp{$@{#foo@}} stands for
1111 @samp{7}, because @samp{tractor} is seven characters.
1114 These variants of variable substitution let you remove part of the
1115 variable's value before substituting it. The @var{prefix} and
1116 @var{suffix} are not mere strings; they are wildcard patterns, just
1117 like the patterns that you use to match multiple file names. But
1118 in this context, they match against parts of the variable value
1119 rather than against file names.
1122 @item $@{@var{variable}%%@var{suffix}@}
1123 Substitute the value of @var{variable}, but first discard from that
1124 variable any portion at the end that matches the pattern @var{suffix}.
1126 If there is more than one alternative for how to match against
1127 @var{suffix}, this construct uses the longest possible match.
1129 Thus, @samp{$@{foo%%r*@}} substitutes @samp{t}, because the largest
1130 match for @samp{r*} at the end of @samp{tractor} is @samp{ractor}.
1132 @item $@{@var{variable}%@var{suffix}@}
1133 Substitute the value of @var{variable}, but first discard from that
1134 variable any portion at the end that matches the pattern @var{suffix}.
1136 If there is more than one alternative for how to match against
1137 @var{suffix}, this construct uses the shortest possible alternative.
1139 Thus, @samp{$@{foo%%r*@}} substitutes @samp{tracto}, because the shortest
1140 match for @samp{r*} at the end of @samp{tractor} is just @samp{r}.
1142 @item $@{@var{variable}##@var{prefix}@}
1143 Substitute the value of @var{variable}, but first discard from that
1144 variable any portion at the beginning that matches the pattern @var{prefix}.
1146 If there is more than one alternative for how to match against
1147 @var{prefix}, this construct uses the longest possible match.
1149 Thus, @samp{$@{foo%%r*@}} substitutes @samp{t}, because the largest
1150 match for @samp{r*} at the end of @samp{tractor} is @samp{ractor}.
1152 @item $@{@var{variable}#@var{prefix}@}
1153 Substitute the value of @var{variable}, but first discard from that
1154 variable any portion at the beginning that matches the pattern @var{prefix}.
1156 If there is more than one alternative for how to match against
1157 @var{prefix}, this construct uses the shortest possible alternative.
1159 Thus, @samp{$@{foo%%r*@}} substitutes @samp{tracto}, because the shortest
1160 match for @samp{r*} at the end of @samp{tractor} is just @samp{r}.