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.
88 The archetypal use of wildcards is for matching against the files in a
89 directory, and making a list of all the matches. This is called
92 You could do this using @code{fnmatch}, by reading the directory entries
93 one by one and testing each one with @code{fnmatch}. But that would be
94 slow (and complex, since you would have to handle subdirectories by
97 The library provides a function @code{glob} to make this particular use
98 of wildcards convenient. @code{glob} and the other symbols in this
99 section are declared in @file{glob.h}.
102 * Calling Glob:: Basic use of @code{glob}.
103 * Flags for Globbing:: Flags that enable various options in @code{glob}.
107 @subsection Calling @code{glob}
109 The result of globbing is a vector of file names (strings). To return
110 this vector, @code{glob} uses a special data type, @code{glob_t}, which
111 is a structure. You pass @code{glob} the address of the structure, and
112 it fills in the structure's fields to tell you about the results.
116 @deftp {Data Type} glob_t
117 This data type holds a pointer to a word vector. More precisely, it
118 records both the address of the word vector and its size.
122 The number of elements in the vector.
125 The address of the vector. This field has type @code{char **}.
128 The offset of the first real element of the vector, from its nominal
129 address in the @code{gl_pathv} field. Unlike the other fields, this
130 is always an input to @code{glob}, rather than an output from it.
132 If you use a nonzero offset, then that many elements at the beginning of
133 the vector are left empty. (The @code{glob} function fills them with
136 The @code{gl_offs} field is meaningful only if you use the
137 @code{GLOB_DOOFFS} flag. Otherwise, the offset is always zero
138 regardless of what is in this field, and the first real element comes at
139 the beginning of the vector.
144 @deftypefun int glob (const char *@var{pattern}, int @var{flags}, int (*@var{errfunc}) (), glob_t *@var{vector_ptr})
145 The function @code{glob} does globbing using the pattern @var{pattern}
146 in the current directory. It puts the result in a newly allocated
147 vector, and store the size and address of this vector into
148 @code{*@var{vector-ptr}}. The argument @var{flags} is a combination of
149 bit flags; see @ref{Flags for Glob}, for details of the flags.
151 The result of globbing is a sequence of file names. The function
152 @code{glob} allocates a string for each resulting word, then
153 allocates a vector of type @code{char **} to store the addresses of
154 these strings. The last element of the vector is a null pointer.
155 This vector is called the @dfn{word vector}.
157 To return this vector, @code{glob} stores both its address and its
158 length (number of elements, not counting the terminating null pointer)
159 into @code{*@var{vector-ptr}}.
161 Normally, @code{glob} sorts the file names alphabetically before
162 returning them. You can turn this off with the flag @code{GLOB_NOSORT}
163 if you want to get the information as fast as possible. Usually it's
164 a good idea to let @code{glob} sort them---if you process the files in
165 alphabetical order, the users will have a feel for the rate of progress
166 that your application is making.
168 If @code{glob} succeeds, it returns 0. Otherwise, it returns one
169 of these error codes:
175 There was an error opening a directory, and you used the flag
176 @code{GLOB_ERR} or your specified @var{errfunc} returned a nonzero
182 The pattern didn't match any existing files. If you use the
183 @code{GLOB_NOCHECK} flag, then you never get this error code, because
184 that flag tells @code{glob} to @emph{pretend} that the pattern matched
190 It was impossible to allocate memory to hold the result.
193 In the event of an error, @code{glob} stores information in
194 @code{*@var{vector-ptr}} about all the matches it has found so far.
197 @node Flags for Globbing
198 @subsection Flags for Globbing
200 This section describes the flags that you can specify in the
201 @var{flags} argument to @code{glob}. Choose the flags you want,
202 and combine them with the C operator @code{|}.
208 Append the words from this expansion to the vector of words produced by
209 previous calls to @code{glob}. This way you can effectively expand
210 several words as if they were concatenated with spaces between them.
212 In order for appending to work, you must not modify the contents of the
213 word vector structure between calls to @code{glob}. And, if you set
214 @code{GLOB_DOOFFS} in the first call to @code{glob}, you must also
215 set it when you append to the results.
220 Leave blank slots at the beginning of the vector of words.
221 The @code{gl_offs} field says how many slots to leave.
222 The blank slots contain null pointers.
227 Give up right away and report an error if there is any difficulty
228 reading the directories that must be read in order to expand @var{pattern}
229 fully. Such difficulties might include a directory in which you don't
230 have the requisite access. Normally, @code{glob} tries its best to keep
231 on going despite any errors, reading whatever directories it can.
233 You can exercise even more control than this by specifying an error-handler
234 function @var{errfunc} when you call @code{glob}. If @var{errfunc} is
235 nonzero, then @code{glob} doesn't give up right away when it can't read
236 a directory; instead, it calls @var{errfunc} with two arguments, like
240 (*@var{errfunc}) (@var{filename}, @var{error-code})
244 The argument @var{filename} is the name of the directory at that
245 @code{glob} couldn't open or couldn't read, and @var{error-code} is
246 the @code{errno} value that was reported to @code{glob}.
248 If the error handler function returns nonzero, then @code{glob} gives up
249 right away. Otherwise, it continues.
254 If the pattern matches the name of a directory, append @samp{/} to the
255 directory's name when returning it.
260 If the pattern doesn't match any file names, return the pattern itself
261 as if it were a file name that had been matched. (Normally, when the
262 pattern doesn't match anything, @code{glob} returns that there were no
268 Don't sort the file names; return them in no particular order.
269 (In practice, the order will depend on the order of the entries in
270 the directory.) The only reason @emph{not} to sort is to save time.
275 Don't treat the @samp{\} character specially in patterns. Normally,
276 @samp{\} quotes the following character, turning off its special meaning
277 (if any) so that it matches only itself. When quoting is enabled, the
278 pattern @samp{\?} matches only the string @samp{?}, because the question
279 mark in the pattern acts like an ordinary character.
281 If you use @code{GLOB_NOESCAPE}, then @samp{\} is an ordinary character.
283 @code{glob} does its work by calling the function @code{fnmatch}
284 repeatedly. @code{glob} handles @code{GLOB_NOESCAPE} by turning on the
285 @code{FNM_NOESCAPE} flag when it calls @code{fnmatch}.
288 @node Regular Expressions
289 @section Regular Expression Matching
291 The GNU C library supports two interfaces for matching regular
292 expressions. One is the standard POSIX.2 interface, and the other is
293 what the GNU system has had for many years.
295 Both interfaces are declared in the header file @file{regex.h}.
296 If you define @code{_GNU_SOURCE}, then the GNU functions, structures
297 and constants are declared. Otherwise, only the POSIX names are
301 * POSIX Regexp Compilation:: Using @code{regcomp} to prepare to match.
302 * Flags for POSIX Regexps:: Syntax variations for @code{regcomp}.
303 * Matching POSIX Regexps:: Using @code{regexec} to match the compiled
304 pattern that you get from @code{regcomp}.
305 * Regexp Subexpressions:: Finding which parts of the string were matched.
306 * Subexpression Complications:: Find points of which parts were matched.
307 * Regexp Cleanup:: Freeing storage; reporting errors.
310 @node POSIX Regexp Compilation
311 @subsection POSIX Regular Expression Compilation
313 Before you can actually match a regular expression, you must
314 @dfn{compile} it. This is not true compilation---it produces a special
315 data structure, not machine instructions. But it is like ordinary
316 compilation in that its purpose is to enable you to ``execute'' the
317 pattern fast. (@xref{Matching POSIX Regexps}, for how to use the
318 compiled regular expression for matching.)
320 There is a special data type for compiled regular expressions:
324 @deftp{Data Type} regex_t
325 This type of object holds a compiled regular expression.
326 It is actually a structure. It has just one field that your programs
331 This field holds the number of parenthetical subexpressions in the
332 regular expression that was compiled.
335 There are several other fields, but we don't describe them here, because
336 only the functions in the library should use them.
339 After you create a @code{regex_t} object, you can compile a regular
340 expression into it by calling @code{regcomp}.
344 @deftypefun int regcomp (regex_t *@var{compiled}, const char *@var{pattern}, int @var{cflags})
345 The function @code{regcomp} ``compiles'' a regular expression into a
346 data structure that you can use with @code{regexec} to match against a
347 string. The compiled regular expression format is designed for
348 efficient matching. @code{regcomp} stores it into @code{*@var{compiled}}.
350 It's up to you to allocate an object of type @code{regex_t} and pass its
351 address to @code{regcomp}.
353 The argument @var{cflags} lets you specify various options that control
354 the syntax and semantics of regular expressions. @xref{Flags for POSIX
357 If you use the flag @code{REG_NOSUB}, then @code{regcomp} omits from
358 the compiled regular expression the information necessary to record
359 how subexpressions actually match. In this case, you might as well
360 pass @code{0} for the @var{matchptr} and @var{nmatch} arguments when
361 you call @code{regexec}.
363 If you don't use @code{REG_NOSUB}, then the compiled regular expression
364 does have the capacity to record how subexpressions match. Also,
365 @code{regcomp} tells you how many subexpressions @var{pattern} has, by
366 storing the number in @code{@var{compiled}->re_nsub}. You can use that
367 value to decide how long an array to allocate to hold information about
368 subexpression matches.
370 @code{regcomp} returns @code{0} if it succeeds in compiling the regular
371 expression; otherwise, it returns a nonzero error code (see the table
372 below). You can use @code{regerror} to produce an error message string
373 describing the reason for a nonzero value; see @ref{Regexp Cleanup}.
377 Here are the possible nonzero values that @code{regcomp} can return:
383 There was an invalid @samp{\@{@dots{}\@}} construct in the regular
384 expression. A valid @samp{\@{@dots{}\@}} construct must contain either
385 a single number, or two numbers in increasing order separated by a
391 There was a syntax error in the regular expression.
396 A repetition operator such as @samp{?} or @samp{*} appeared in a bad
397 position (with no preceding subexpression to act on).
402 The regular expression referred to an invalid collating element (one not
403 defined in the current locale for string collation). @xref{Locale
409 The regular expression referred to an invalid character class name.
414 The regular expression ended with @samp{\}.
419 There was an invalid number in the @samp{\@var{digit}} construct.
424 There were unbalanced square brackets in the regular expression.
429 An extended regular expression had unbalanced parentheses,
430 or a basic regular expression had unbalanced @samp{\(} and @samp{\)}.
435 The regular expression had unbalanced @samp{\@{} and @samp{\@}}.
440 One of the endpoints in a range expression was invalid.
445 @code{regcomp} or @code{regexec} ran out of memory.
448 @node Flags for POSIX Regexps
449 @subsection Flags for POSIX Regular Expressions
451 These are the bit flags that you can use in the @var{cflags} operand when
452 compiling a regular expression with @code{regcomp}.
458 Treat the pattern as an extended regular expression, rather than as a
459 basic regular expression.
464 Ignore case when matching letters.
469 Don't bother storing the contents of the @var{matches_ptr} array.
474 Treat a newline in @var{string} as dividing @var{string} into multiple
475 lines, so that @samp{$} can match before the newline and @samp{^} can
476 match after. Also, don't permit @samp{.} to match a newline, and don't
477 permit @samp{[^@dots{}]} to match a newline.
479 Otherwise, newline acts like any other ordinary character.
482 @node Matching POSIX Regexps
483 @subsection Matching a Compiled POSIX Regular Expression
485 Once you have compiled a regular expression, as described in @ref{POSIX
486 Regexp Compilation}, you can match it against strings using
487 @code{regexec}. A match anywhere inside the string counts as success,
488 unless the regular expression contains anchor characters (@samp{^} or
493 @deftypefun int regexec (regex_t *@var{compiled}, char *@var{string}, size_t @var{nmatch}, regmatch_t @var{matchptr} @t{[]}, int @var{eflags})
494 This function tries to match the compiled regular expression
495 @code{*@var{compiled}} against @var{string}.
497 @code{regexec} returns @code{0} if the regular expression matches;
498 otherwise, it returns a nonzero value. See the table below for
499 what nonzero values mean. You can use @code{regerror} to produce an
500 error message string describing the reason for a nonzero value;
501 see @ref{Regexp Cleanup}.
503 The argument @var{eflags} is a word of bit flags that enable various
506 If you want to get information about what part of @var{string} actually
507 matched the regular expression or its subexpressions, use the arguments
508 @var{matchptr} and @var{nmatch}. Otherwise, pass @code{0} for
509 @var{nmatch}, and @code{NULL} for @var{matchptr}. @xref{Regexp
513 You must match the regular expression with the same set of current
514 locales that were in effect when you compiled the regular expression.
516 The function @code{regexec} accepts the following flags in the
517 @var{eflags} argument:
523 Do not regard the beginning of the specified string as the beginning of
524 a line; more generally, don't make any assumptions about what text might
530 Do not regard the end of the specified string as the end of a line; more
531 generally, don't make any assumptions about what text might follow it.
534 Here are the possible nonzero values that @code{regexec} can return:
540 The pattern didn't match the string. This isn't really an error.
545 @code{regcomp} or @code{regexec} ran out of memory.
548 @node Regexp Subexpressions
549 @subsection Subexpressions Match Results
551 When @code{regexec} matches parenthetical subexpressions of
552 @var{pattern}, it records which parts of @var{string} they match. It
553 returns that information by storing the offsets into an array whose
554 elements are structures of type @code{regmatch_t}. The first element of
555 the array records the part of the string that matched the entire regular
556 expression. Each other element of the array records the beginning and
557 end of the part that matched a single parenthetical subexpression.
561 @deftp {Data Type} regmatch_t
562 This is the data type of the @var{matcharray} array that you pass to
563 @code{regexec}. It containes two structure fields, as follows:
567 The offset in @var{string} of the beginning of a substring. Add this
568 value to @var{string} to get the address of that part.
571 The offset in @var{string} of the end of the substring.
577 @deftp {Data Type} regoff_t
578 @code{regoff_t} is an alias for another signed integer type.
579 The fields of @code{regmatch_t} have type @code{regoff_t}.
582 The @code{regmatch_t} elements correspond to subexpressions
583 positionally; the first element records where the first subexpression
584 matched, the second element records the second subexpression, and so on.
585 The order of the subexpressions is the order in which they begin.
587 When you call @code{regexec}, you specify how long the @var{matchptr}
588 array is, with the @var{nmatch} argument. This tells @code{regexec} how
589 many elements to store. If the actual regular expression has more than
590 @var{nmatch} subexpressions, then you won't get offset information about
591 the rest of them. But this doesn't alter whether the pattern matches a
592 particular string or not.
594 If you don't want @code{regexec} to return any information about where
595 the subexpressions matched, you can either supply @code{0} for
596 @var{nmatch}, or use the flag @code{REG_NOSUB} when you compile the
597 pattern with @code{regcomp}.
599 @node Subexpression Complications
600 @subsection Complications in Subexpression Matching
602 Sometimes a subexpression matches a substring of no characters. This
603 happens when @samp{f\(o*\)} matches the string @samp{fum}. (It really
604 matches just the @samp{f}.) In this case, both of the offsets identify
605 the point in the string where the null substring was found. In this
606 example, the offsets are both @code{1}.
608 Sometimes the entire regular expression can match without using some of
609 its subexpressions at all---for example, when @samp{ba\(na\)*} matches the
610 string @samp{ba}, the parenthetical subexpression is not used. When
611 this happens, @code{regexec} stores @code{-1} in both fields of the
612 element for that subexpression.
614 Sometimes matching the entire regular expression can match can use a
615 particular subexpression more than once---for example, when
616 @samp{ba\(na\)*} matches the string @samp{bananana}, the parenthetical
617 subexpression matches three times. When this happens, @code{regexec}
618 usually stores the offsets of the last part of the string that matched
619 the subexpression. In the case of @samp{bananana}, these offsets are
620 @code{6} and @code{8}.
622 But the last match is not always the one that is chosen. It's more
623 accurate to say that the last @emph{opportunity} to match is the one
624 that takes precedence. What this means is that when one subexpression
625 appears within another, then the results reported for the inner
626 subexpression reflect whatever happened on the last match of the outer
627 subexpression. For an example, consider @samp{\(ba\(na\)*s \)} matching
628 the string @samp{bananas bas }. The last time the inner expression
629 actually matches is near the end of the first word. But it is
630 @emph{considered} again in the second word, and fails to match there.
631 @code{regexec} reports nonuse of the ``na'' subexpression.
633 Another place where this rule applies is when @samp{\(ba\(na\)*s
634 \|nefer\(ti\)* \)*} matches @samp{bananas nefertiti}. The ``na''
635 subexpression does match in the first word, but it doesn't match in the
636 second word because the other alternative is used there. Once again,
637 the second repetition of the outer subexpression overrides the first,
638 and within that second repetition, the ``na'' subexpression is not used.
639 So @code{regexec} reports nonuse of the ``na'' subexpression.
642 @subsection POSIX Regexp Matching Cleanup
644 When you are finished using a compiled regular expression, you can
645 free the storage it uses by calling @code{regfree}.
649 @deftypefun void regfree (regex_t *@var{compiled})
650 Calling @code{regfree} frees all the storage that @code{*@var{compiled}}
651 points to. This includes various fields of the @code{regex_t} structure
652 that aren't documented in this manual.
654 @code{regfree} does not free the object @code{*@var{compiled}} itself.
657 You should always free the space in a @code{regex_t} structure with
658 @code{regfree} before using the structure to compile another regular
661 When @code{regcomp} or @code{regexec} reports an error, you can use
662 the function @code{regerror} to turn it into an error message string.
666 @deftypefun size_t regerror (int @var{errcode}, regex_t *@var{compiled}, char *@var{buffer}, size_t @var{length})
667 This function produces an error message string for the error code
668 @var{errcode}, and stores the string in @var{length} bytes of memory
669 starting at @var{buffer}. For the @var{compiled} argument, supply the
670 same compiled regular expression structure that @code{regcomp} or
671 @code{regexec} was working with when it got the error. Alternatively,
672 you can supply @code{NULL} for @var{compiled}; you will still get a
673 meaningful error message, but it might not be as detailed.
675 If the error message can't fit in @var{length} bytes (including a
676 terminating null character), then @code{regerror} truncates it.
677 The string that @code{regerror} stores is always null-terminated
678 even if it has been truncated.
680 The return value of @code{regerror} is the minimum length needed to
681 store the entire error message. If this is less than @var{length}, then
682 the error message was not truncated, and you can use it. Otherwise, you
683 should call @code{regerror} again with a larger buffer.
687 @section Shell-Style Word Expansion
688 @cindex word expansion
689 @cindex expansion of shell words
691 @dfn{Word expansion} means the process of splitting a string into
692 @dfn{words} and substituting for variables, commands, and wildcards
693 just as the shell does.
695 For example, when you write @samp{ls -l foo.c}, this string is split
696 into three separate words---@samp{ls}, @samp{-l} and @samp{foo.c}.
697 This is the most basic function of word expansion.
699 When you write @samp{ls *.c}, this can become many words, because
700 the word @samp{*.c} can be replaced with any number of file names.
701 This is called @dfn{wildcard expansion}, and it is also a part of
704 When you use @samp{echo $PATH} to print your path, you are taking
705 advantage of @dfn{variable substitution}, which is also part of word
708 Ordinary programs can perform word expansion just like the shell by
709 calling the library function @code{wordexp}.
712 * Expansion Stages:: What word expansion does to a string.
713 * Calling Wordexp:: How to call @code{wordexp}.
714 * Flags for Wordexp:: Options you can enable in @code{wordexp}.
715 * Wordexp Example:: A sample program that does word expansion.
718 @node Expansion Stages
719 @subsection The Stages of Word Expansion
721 When word expansion is applied to a sequence of words, it performs the
722 following transformations in the order shown here:
726 @cindex tilde expansion
727 @dfn{Tilde expansion}: Replacement of @samp{~foo} with the name of
728 the home directory of @samp{foo}.
731 Next, three different transformations are applied in the same step,
736 @cindex variable substitution
737 @cindex substitution of variables and commands
738 @dfn{Variable substitution}: The substitution of environment variables
739 for references such as @samp{$foo}.
742 @cindex command substitution
743 @dfn{Command substitution}: Replacement of constructs such as
744 @samp{`cat foo`} or @samp{$(cat foo)} with the output from the inner
748 @cindex arithmetic expansion
749 @dfn{Arithmetic expansion}: Replacement of constructs such as
750 @samp{$(($x-1))} with the result of the arithmetic computation.
754 @cindex field splitting
755 @dfn{Field splitting}: subdivision of the text into @dfn{words}.
758 @cindex wildcard expansion
759 @dfn{Wildcard expansion}: The replacement of a construct such as @samp{*.c}
760 with a list of @samp{.c} file names. Wildcard expansion applies to an
761 entire word at a time, and replaces that word with 0 or more file names
762 that are themselves words.
765 @cindex quote removal
766 @cindex removal of quotes
767 @dfn{Quote removal}: The deletion of string-quotes, now that they have
768 done their job by inhibiting the above transformations when appropriate.
771 For the details of these transformations, and how to write the constructs
772 that use them, see @cite{The BASH Manual} (to appear).
774 @node Calling Wordexp
775 @subsection Calling @code{wordexp}
777 All the functions, constants and data types for word expansion are
778 declared in the header file @file{wordexp.h}.
780 Word expansion produces a vector of words (strings). To return this
781 vector, @code{wordexp} uses a special data type, @code{wordexp_t}, which
782 is a structure. You pass @code{wordexp} the address of the structure,
783 and it fills in the structure's fields to tell you about the results.
785 @deftp {Data Type} {wordexp_t}
786 This data type holds a pointer to a word vector. More precisely, it
787 records both the address of the word vector and its size.
791 The number of elements in the vector.
794 The address of the vector. This field has type @code{char **}.
797 The offset of the first real element of the vector, from its nominal
798 address in the @code{we_wordv} field. Unlike the other fields, this
799 is always an input to @code{wordexp}, rather than an output from it.
801 If you use a nonzero offset, then that many elements at the beginning of
802 the vector are left empty. (The @code{wordexp} function fills them with
805 The @code{we_offs} field is meaningful only if you use the
806 @code{WRDE_DOOFFS} flag. Otherwise, the offset is always zero
807 regardless of what is in this field, and the first real element comes at
808 the beginning of the vector.
811 @deftypefun int wordexp (const char *@var{words}, wordexp_t *@var{word-vector-ptr}, int @var{flags})
812 Perform word expansion on the string @var{words}, putting the result in
813 a newly allocated vector, and store the size and address of this vector
814 into @code{*@var{word-vector-ptr}}. The argument @var{flags} is a
815 combination of bit flags; see @ref{Flags for Wordexp}, for details of
818 You shouldn't use any of the characters @samp{|&;<>} in the string
819 @var{words} unless they are quoted; likewise for newline. If you use
820 these characters unquoted, you will get the @code{WRDE_BADCHAR} error
821 code. Don't use parentheses or braces unless they are quoted or part of
822 a word expansion construct. If you use quotation characters @samp{'"`},
823 they should come in pairs that balance.
825 The results of word expansion are a sequence of words. The function
826 @code{wordexp} allocates a string for each resulting word, then
827 allocates a vector of type @code{char **} to store the addresses of
828 these strings. The last element of the vector is a null pointer.
829 This vector is called the @dfn{word vector}.
831 To return this vector, @code{wordexp} stores both its address and its
832 length (number of elements, not counting the terminating null pointer)
833 into @code{*@var{word-vector-ptr}}.
835 If @code{wordexp} succeeds, it returns 0. Otherwise, it returns one
836 of these error codes:
842 The input string @var{words} contains an unquoted invalid character such
848 The input string refers to an undefined shell variable, and you used the flag
849 @code{WRDE_UNDEF} to forbid such references.
854 The input string uses command substitution, and you used the flag
855 @code{WRDE_NOCMD} to forbid command substitution.
860 It was impossible to allocate memory to hold the result. In this case,
861 @code{wordexp} can store part of the results---as much as it could
867 There was a syntax error in the input string. For example, an unmatched
868 quoting character is a syntax error.
872 @deftypefun void wordfree (wordexp_t *@var{word-vector-ptr})
873 Free the storage used for the word-strings and vector that
874 @code{*@var{word-vector-ptr}} points to. This does not free the
875 structure @code{*@var{word-vector-ptr}} itself---only the other
876 structure pointed to by it.
879 @node Flags for Wordexp
880 @subsection Flags for Word Expansion
882 This section describes the flags that you can specify in the
883 @var{flags} argument to @code{wordexp}. Choose the flags you want,
884 and combine them with the C operator @code{|}.
890 Append the words from this expansion to the vector of words produced by
891 previous calls to @code{wordexp}. This way you can effectively expand
892 several words as if they were concatenated with spaces between them.
894 In order for appending to work, you must not modify the contents of the
895 word vector structure between calls to @code{wordexp}. And, if you set
896 @code{WRDE_DOOFFS} in the first call to @code{wordexp}, you must also
897 set it when you append to the results.
902 Leave blank slots at the beginning of the vector of words.
903 The @code{we_offs} field says how many slots to leave.
904 The blank slots contain null pointers.
909 Don't do command substitution; if the input requests command substitution,
915 Reuse a word vector made by a previous call to @code{wordexp}.
916 Instead of allocating a new vector of words, this call to @code{wordexp}
917 will use the vector that already exists (making it larger if necessary).
922 Do show any error messages printed by commands run by command substitution.
923 More precisely, allow these commands to inherit the standard error output
924 stream of the current process. By default, @code{wordexp} gives these
925 commands a standard error stream that discards all output.
930 If the input refers to a shell variable that is not defined, report an
934 @node Wordexp Example
935 @subsection @code{wordexp} Example
937 Here is an example of using @code{wordexp} to expand several strings
938 and use the results to run a shell command. It also shows the use of
939 @code{WRDE_APPEND} to concatenate the expansions and of @code{wordfree}
940 to free the space allocated by @code{wordexp}.
944 expand_and_execute (char *program, char *options)
951 /* @r{Expand the string for the program to run.} */
952 fail = wordexp (program, &result, 0);
954 /* @r{If the error was @code{WRDE_NOSPACE},}
955 @r{then perhaps part of the result was allocated.} */
956 if (fail == WRDE_NOSPACE)
961 /* @r{Expand the strings specified for the arguments.} */
962 for (i = 0; args[i]; i++) @{
963 fail = wordexp (options, &result, WRDE_APPEND);
972 execv (result.we_wordv[0], result.we_wordv);
976 /* @r{The fork failed. Report failure.} */
979 /* @r{This is the parent process. Wait for the child to complete.} */
980 if (waitpid (pid, &status, 0) != pid)
989 In practice, since @code{wordexp} is executed by running a subshell, it
990 would be faster to do this by concatenating the strings with spaces
991 between them and running that as a shell command using @samp{sh -c}.
993 @c No sense finishing this for here.
995 @node Tilde Expansion
996 @subsection Details of Tilde Expansion
998 It's a standard part of shell syntax that you can use @samp{~} at the
999 beginning of a file name to stand for your own home directory. You
1000 can use @samp{~@var{user}} to stand for @var{user}'s home directory.
1002 @dfn{Tilde expansion} is the process of converting these abbreviations
1003 to the directory names that they stand for.
1005 Tilde expansion applies to the @samp{~} plus all following characters up
1006 to whitespace or a slash. It takes place only at the beginning of a
1007 word, and only if none of the characters to be transformed is quoted in
1010 Plain @samp{~} uses the value of the environment variable @code{HOME}
1011 as the proper home directory name. @samp{~} followed by a user name
1012 uses @code{getpwname} to look up that user in the user database, and
1013 uses whatever directory is recorded there. Thus, @samp{~} followed
1014 by your own name can give different results from plain @samp{~}, if
1015 the value of @code{HOME} is not really your home directory.
1017 @node Variable Substitution
1018 @subsection Details of Variable Substitution
1020 Part of ordinary shell syntax is the use of @samp{$@var{variable}} to
1021 substitute the value of a shell variable into a command. This is called
1022 @dfn{variable substitution}, and it is one part of doing word expansion.
1024 There are two basic ways you can write a variable reference for
1028 @item $@{@var{variable}@}
1029 If you write braces around the variable name, then it is completely
1030 unambiguous where the variable name ends. You can concatenate
1031 additional letters onto the end of the variable value by writing them
1032 immediately after the close brace. For example, @samp{$@{foo@}s}
1033 expands into @samp{tractors}.
1035 @item $@var{variable}
1036 If you do not put braces around the variable name, then the variable
1037 name consists of all the alphanumeric characters and underscores that
1038 follow the @samp{$}. The next punctuation character ends the variable
1039 name. Thus, @samp{$foo-bar} refers to the variable @code{foo} and expands
1040 into @samp{tractor-bar}.
1043 When you use braces, you can also use various constructs to modify the
1044 value that is substituted, or test it in various ways.
1047 @item $@{@var{variable}:-@var{default}@}
1048 Substitute the value of @var{variable}, but if that is empty or
1049 undefined, use @var{default} instead.
1051 @item $@{@var{variable}:=@var{default}@}
1052 Substitute the value of @var{variable}, but if that is empty or
1053 undefined, use @var{default} instead and set the variable to
1056 @item $@{@var{variable}:?@var{message}@}
1057 If @var{variable} is defined and not empty, substitute its value.
1059 Otherwise, print @var{message} as an error message on the standard error
1060 stream, and consider word expansion a failure.
1062 @c ??? How does wordexp report such an error?
1064 @item $@{@var{variable}:+@var{replacement}@}
1065 Substitute @var{replacement}, but only if @var{variable} is defined and
1066 nonempty. Otherwise, substitute nothing for this construct.
1070 @item $@{#@var{variable}@}
1071 Substitute a numeral which expresses in base ten the number of
1072 characters in the value of @var{variable}. @samp{$@{#foo@}} stands for
1073 @samp{7}, because @samp{tractor} is seven characters.
1076 These variants of variable substitution let you remove part of the
1077 variable's value before substituting it. The @var{prefix} and
1078 @var{suffix} are not mere strings; they are wildcard patterns, just
1079 like the patterns that you use to match multiple file names. But
1080 in this context, they match against parts of the variable value
1081 rather than against file names.
1084 @item $@{@var{variable}%%@var{suffix}@}
1085 Substitute the value of @var{variable}, but first discard from that
1086 variable any portion at the end that matches the pattern @var{suffix}.
1088 If there is more than one alternative for how to match against
1089 @var{suffix}, this construct uses the longest possible match.
1091 Thus, @samp{$@{foo%%r*@}} substitutes @samp{t}, because the largest
1092 match for @samp{r*} at the end of @samp{tractor} is @samp{ractor}.
1094 @item $@{@var{variable}%@var{suffix}@}
1095 Substitute the value of @var{variable}, but first discard from that
1096 variable any portion at the end that matches the pattern @var{suffix}.
1098 If there is more than one alternative for how to match against
1099 @var{suffix}, this construct uses the shortest possible alternative.
1101 Thus, @samp{$@{foo%%r*@}} substitutes @samp{tracto}, because the shortest
1102 match for @samp{r*} at the end of @samp{tractor} is just @samp{r}.
1104 @item $@{@var{variable}##@var{prefix}@}
1105 Substitute the value of @var{variable}, but first discard from that
1106 variable any portion at the beginning that matches the pattern @var{prefix}.
1108 If there is more than one alternative for how to match against
1109 @var{prefix}, this construct uses the longest possible match.
1111 Thus, @samp{$@{foo%%r*@}} substitutes @samp{t}, because the largest
1112 match for @samp{r*} at the end of @samp{tractor} is @samp{ractor}.
1114 @item $@{@var{variable}#@var{prefix}@}
1115 Substitute the value of @var{variable}, but first discard from that
1116 variable any portion at the beginning that matches the pattern @var{prefix}.
1118 If there is more than one alternative for how to match against
1119 @var{prefix}, this construct uses the shortest possible alternative.
1121 Thus, @samp{$@{foo%%r*@}} substitutes @samp{tracto}, because the shortest
1122 match for @samp{r*} at the end of @samp{tractor} is just @samp{r}.