Update.
[glibc.git] / manual / pattern.texi
blob1a90ddc2405fb9cc22124e5b280f02758dbbd944
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}.
102 @end table
104 @node Globbing
105 @section Globbing
107 @cindex globbing
108 The archetypal use of wildcards is for matching against the files in a
109 directory, and making a list of all the matches.  This is called
110 @dfn{globbing}.
112 You could do this using @code{fnmatch}, by reading the directory entries
113 one by one and testing each one with @code{fnmatch}.  But that would be
114 slow (and complex, since you would have to handle subdirectories by
115 hand).
117 The library provides a function @code{glob} to make this particular use
118 of wildcards convenient.  @code{glob} and the other symbols in this
119 section are declared in @file{glob.h}.
121 @menu
122 * Calling Glob::             Basic use of @code{glob}.
123 * Flags for Globbing::       Flags that enable various options in @code{glob}.
124 * More Flags for Globbing::  GNU specific extensions to @code{glob}.
125 @end menu
127 @node Calling Glob
128 @subsection Calling @code{glob}
130 The result of globbing is a vector of file names (strings).  To return
131 this vector, @code{glob} uses a special data type, @code{glob_t}, which
132 is a structure.  You pass @code{glob} the address of the structure, and
133 it fills in the structure's fields to tell you about the results.
135 @comment glob.h
136 @comment POSIX.2
137 @deftp {Data Type} glob_t
138 This data type holds a pointer to a word vector.  More precisely, it
139 records both the address of the word vector and its size.  The GNU
140 implementation contains some more fields which are non-standard
141 extensions.
143 @table @code
144 @item gl_pathc
145 The number of elements in the vector, excluding the initial null entries
146 if the GLOB_DOOFFS flag is used (see gl_offs below).
148 @item gl_pathv
149 The address of the vector.  This field has type @w{@code{char **}}.
151 @item gl_offs
152 The offset of the first real element of the vector, from its nominal
153 address in the @code{gl_pathv} field.  Unlike the other fields, this
154 is always an input to @code{glob}, rather than an output from it.
156 If you use a nonzero offset, then that many elements at the beginning of
157 the vector are left empty.  (The @code{glob} function fills them with
158 null pointers.)
160 The @code{gl_offs} field is meaningful only if you use the
161 @code{GLOB_DOOFFS} flag.  Otherwise, the offset is always zero
162 regardless of what is in this field, and the first real element comes at
163 the beginning of the vector.
165 @item gl_closedir
166 The address of an alternative implementation of the @code{closedir}
167 function.  It is used if the @code{GLOB_ALTDIRFUNC} bit is set in
168 the flag parameter.  The type of this field is
169 @w{@code{void (*) (void *)}}.
171 This is a GNU extension.
173 @item gl_readdir
174 The address of an alternative implementation of the @code{readdir}
175 function used to read the contents of a directory.  It is used if the
176 @code{GLOB_ALTDIRFUNC} bit is set in the flag parameter.  The type of
177 this field is @w{@code{struct dirent *(*) (void *)}}.
179 This is a GNU extension.
181 @item gl_opendir
182 The address of an alternative implementation of the @code{opendir}
183 function.  It is used if the @code{GLOB_ALTDIRFUNC} bit is set in
184 the flag parameter.  The type of this field is
185 @w{@code{void *(*) (const char *)}}.
187 This is a GNU extension.
189 @item gl_stat
190 The address of an alternative implementation of the @code{stat} function
191 to get information about an object in the filesystem.  It is used if the
192 @code{GLOB_ALTDIRFUNC} bit is set in the flag parameter.  The type of
193 this field is @w{@code{int (*) (const char *, struct stat *)}}.
195 This is a GNU extension.
197 @item gl_lstat
198 The address of an alternative implementation of the @code{lstat}
199 function to get information about an object in the filesystems, not
200 following symbolic links.  It is used if the @code{GLOB_ALTDIRFUNC} bit
201 is set in the flag parameter.  The type of this field is @code{@w{int
202 (*) (const char *,} @w{struct stat *)}}.
204 This is a GNU extension.
205 @end table
206 @end deftp
208 @comment glob.h
209 @comment POSIX.2
210 @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})
211 The function @code{glob} does globbing using the pattern @var{pattern}
212 in the current directory.  It puts the result in a newly allocated
213 vector, and stores the size and address of this vector into
214 @code{*@var{vector-ptr}}.  The argument @var{flags} is a combination of
215 bit flags; see @ref{Flags for Globbing}, for details of the flags.
217 The result of globbing is a sequence of file names.  The function
218 @code{glob} allocates a string for each resulting word, then
219 allocates a vector of type @code{char **} to store the addresses of
220 these strings.  The last element of the vector is a null pointer.
221 This vector is called the @dfn{word vector}.
223 To return this vector, @code{glob} stores both its address and its
224 length (number of elements, not counting the terminating null pointer)
225 into @code{*@var{vector-ptr}}.
227 Normally, @code{glob} sorts the file names alphabetically before
228 returning them.  You can turn this off with the flag @code{GLOB_NOSORT}
229 if you want to get the information as fast as possible.  Usually it's
230 a good idea to let @code{glob} sort them---if you process the files in
231 alphabetical order, the users will have a feel for the rate of progress
232 that your application is making.
234 If @code{glob} succeeds, it returns 0.  Otherwise, it returns one
235 of these error codes:
237 @table @code
238 @comment glob.h
239 @comment POSIX.2
240 @item GLOB_ABORTED
241 There was an error opening a directory, and you used the flag
242 @code{GLOB_ERR} or your specified @var{errfunc} returned a nonzero
243 value.
244 @iftex
245 See below
246 @end iftex
247 @ifinfo
248 @xref{Flags for Globbing},
249 @end ifinfo
250 for an explanation of the @code{GLOB_ERR} flag and @var{errfunc}.
252 @comment glob.h
253 @comment POSIX.2
254 @item GLOB_NOMATCH
255 The pattern didn't match any existing files.  If you use the
256 @code{GLOB_NOCHECK} flag, then you never get this error code, because
257 that flag tells @code{glob} to @emph{pretend} that the pattern matched
258 at least one file.
260 @comment glob.h
261 @comment POSIX.2
262 @item GLOB_NOSPACE
263 It was impossible to allocate memory to hold the result.
264 @end table
266 In the event of an error, @code{glob} stores information in
267 @code{*@var{vector-ptr}} about all the matches it has found so far.
268 @end deftypefun
270 @node Flags for Globbing
271 @subsection Flags for Globbing
273 This section describes the flags that you can specify in the
274 @var{flags} argument to @code{glob}.  Choose the flags you want,
275 and combine them with the C bitwise OR operator @code{|}.
277 @table @code
278 @comment glob.h
279 @comment POSIX.2
280 @item GLOB_APPEND
281 Append the words from this expansion to the vector of words produced by
282 previous calls to @code{glob}.  This way you can effectively expand
283 several words as if they were concatenated with spaces between them.
285 In order for appending to work, you must not modify the contents of the
286 word vector structure between calls to @code{glob}.  And, if you set
287 @code{GLOB_DOOFFS} in the first call to @code{glob}, you must also
288 set it when you append to the results.
290 Note that the pointer stored in @code{gl_pathv} may no longer be valid
291 after you call @code{glob} the second time, because @code{glob} might
292 have relocated the vector.  So always fetch @code{gl_pathv} from the
293 @code{glob_t} structure after each @code{glob} call; @strong{never} save
294 the pointer across calls.
296 @comment glob.h
297 @comment POSIX.2
298 @item GLOB_DOOFFS
299 Leave blank slots at the beginning of the vector of words.
300 The @code{gl_offs} field says how many slots to leave.
301 The blank slots contain null pointers.
303 @comment glob.h
304 @comment POSIX.2
305 @item GLOB_ERR
306 Give up right away and report an error if there is any difficulty
307 reading the directories that must be read in order to expand @var{pattern}
308 fully.  Such difficulties might include a directory in which you don't
309 have the requisite access.  Normally, @code{glob} tries its best to keep
310 on going despite any errors, reading whatever directories it can.
312 You can exercise even more control than this by specifying an
313 error-handler function @var{errfunc} when you call @code{glob}.  If
314 @var{errfunc} is not a null pointer, then @code{glob} doesn't give up
315 right away when it can't read a directory; instead, it calls
316 @var{errfunc} with two arguments, like this:
318 @smallexample
319 (*@var{errfunc}) (@var{filename}, @var{error-code})
320 @end smallexample
322 @noindent
323 The argument @var{filename} is the name of the directory that
324 @code{glob} couldn't open or couldn't read, and @var{error-code} is the
325 @code{errno} value that was reported to @code{glob}.
327 If the error handler function returns nonzero, then @code{glob} gives up
328 right away.  Otherwise, it continues.
330 @comment glob.h
331 @comment POSIX.2
332 @item GLOB_MARK
333 If the pattern matches the name of a directory, append @samp{/} to the
334 directory's name when returning it.
336 @comment glob.h
337 @comment POSIX.2
338 @item GLOB_NOCHECK
339 If the pattern doesn't match any file names, return the pattern itself
340 as if it were a file name that had been matched.  (Normally, when the
341 pattern doesn't match anything, @code{glob} returns that there were no
342 matches.)
344 @comment glob.h
345 @comment POSIX.2
346 @item GLOB_NOSORT
347 Don't sort the file names; return them in no particular order.
348 (In practice, the order will depend on the order of the entries in
349 the directory.)  The only reason @emph{not} to sort is to save time.
351 @comment glob.h
352 @comment POSIX.2
353 @item GLOB_NOESCAPE
354 Don't treat the @samp{\} character specially in patterns.  Normally,
355 @samp{\} quotes the following character, turning off its special meaning
356 (if any) so that it matches only itself.  When quoting is enabled, the
357 pattern @samp{\?} matches only the string @samp{?}, because the question
358 mark in the pattern acts like an ordinary character.
360 If you use @code{GLOB_NOESCAPE}, then @samp{\} is an ordinary character.
362 @code{glob} does its work by calling the function @code{fnmatch}
363 repeatedly.  It handles the flag @code{GLOB_NOESCAPE} by turning on the
364 @code{FNM_NOESCAPE} flag in calls to @code{fnmatch}.
365 @end table
367 @node More Flags for Globbing
368 @subsection More Flags for Globbing
370 Beside the flags described in the last section, the GNU implementation of
371 @code{glob} allows a few more flags which are also defined in the
372 @file{glob.h} file.  Some of the extensions implement functionality
373 which is available in modern shell implementations.
375 @table @code
376 @comment glob.h
377 @comment GNU
378 @item GLOB_PERIOD
379 The @code{.} character (period) is treated special.  It cannot be
380 matched by wildcards.  @xref{Wildcard Matching}, @code{FNM_PERIOD}.
382 @comment glob.h
383 @comment GNU
384 @item GLOB_MAGCHAR
385 The @code{GLOB_MAGCHAR} value is not to be given to @code{glob} in the
386 @var{flags} parameter.  Instead, @code{glob} sets this bit in the
387 @var{gl_flags} element of the @var{glob_t} structure provided as the
388 result if the pattern used for matching contains any wildcard character.
390 @comment glob.h
391 @comment GNU
392 @item GLOB_ALTDIRFUNC
393 Instead of the using the using the normal functions for accessing the
394 filesystem the @code{glob} implementation uses the user-supplied
395 functions specified in the structure pointed to by @var{pglob}
396 parameter.  For more information about the functions refer to the
397 sections about directory handling see @ref{Accessing Directories}, and
398 @ref{Reading Attributes}.
400 @comment glob.h
401 @comment GNU
402 @item GLOB_BRACE
403 If this flag is given the handling of braces in the pattern is changed.
404 It is now required that braces appear correctly grouped.  I.e., for each
405 opening brace there must be a closing one.  Braces can be used
406 recursively.  So it is possible to define one brace expression in
407 another one.  It is important to note that the range of each brace
408 expression is completely contained in the outer brace expression (if
409 there is one).
411 The string between the matching braces is separated into single
412 expressions by splitting at @code{,} (comma) characters.  The commas
413 themself are discarded.  Please note what we said above about recursive
414 brace expressions.  The commas used to separate the subexpressions must
415 be at the same level.  Commas in brace subexpressions are not matched.
416 They are used during expansion of the brace expression of the deeper
417 level.  The example below shows this
419 @smallexample
420 glob ("@{foo/@{,bar,biz@},baz@}", GLOB_BRACE, NULL, &result)
421 @end smallexample
423 @noindent
424 is equivalent to the sequence
426 @smallexample
427 glob ("foo/", GLOB_BRACE, NULL, &result)
428 glob ("foo/bar", GLOB_BRACE|GLOB_APPEND, NULL, &result)
429 glob ("foo/biz", GLOB_BRACE|GLOB_APPEND, NULL, &result)
430 glob ("baz", GLOB_BRACE|GLOB_APPEND, NULL, &result)
431 @end smallexample
433 @noindent
434 if we leave aside error handling.
436 @comment glob.h
437 @comment GNU
438 @item GLOB_NOMAGIC
439 If the pattern contains no wildcard constructs (it is a literal file name),
440 return it as the sole ``matching'' word, even if no file exists by that name.
442 @comment glob.h
443 @comment GNU
444 @item GLOB_TILDE
445 If this flag is used the character @code{~} (tilde) is handled special
446 if it appears at the beginning of the pattern.  Instead of being taken
447 verbatim it is used to represent the home directory of a known user.
449 If @code{~} is the only character in pattern or it is followed by a
450 @code{/} (slash), the home directory of the process owner is
451 substituted.  Using @code{getlogin} and @code{getpwnam} the information
452 is read from the system databases.  As an example take user @code{bart}
453 with his home directory at @file{/home/bart}.  For him a call like
455 @smallexample
456 glob ("~/bin/*", GLOB_TILDE, NULL, &result)
457 @end smallexample
459 @noindent
460 would return the contents of the directory @file{/home/bart/bin}.
461 Instead of referring to the own home directory it is also possible to
462 name the home directory of other users.  To do so one has to append the
463 user name after the tilde character.  So the contents of user
464 @code{homer}'s @file{bin} directory can be retrieved by
466 @smallexample
467 glob ("~homer/bin/*", GLOB_TILDE, NULL, &result)
468 @end smallexample
470 If the user name is not valid or the home directory cannot be determined
471 for some reason the pattern is left untouched and itself used as the
472 result.  I.e., if in the last example @code{home} is not available the
473 tilde expansion yields to @code{"~homer/bin/*"} and @code{glob} is not
474 looking for a directory named @code{~homer}.
476 This functionality is equivalent to what is available in C-shells if the
477 @code{nonomatch} flag is set.
479 @comment glob.h
480 @comment GNU
481 @item GLOB_TILDE_CHECK
482 If this flag is used @code{glob} behaves like as if @code{GLOB_TILDE} is
483 given.  The only difference is that if the user name is not available or
484 the home directory cannot be determined for other reasons this leads to
485 an error.  @code{glob} will return @code{GLOB_NOMATCH} instead of using
486 the pattern itself as the name.
488 This functionality is equivalent to what is available in C-shells if
489 @code{nonomatch} flag is not set.
491 @comment glob.h
492 @comment GNU
493 @item GLOB_ONLYDIR
494 If this flag is used the globbing function takes this as a
495 @strong{hint} that the caller is only interested in directories
496 matching the pattern.  If the information about the type of the file
497 is easily available non-directories will be rejected but no extra
498 work will be done to determine the information for each file.  I.e.,
499 the caller must still be able to filter directories out.
501 This functionality is only available with the GNU @code{glob}
502 implementation.  It is mainly used internally to increase the
503 performance but might be useful for a user as well and therefore is
504 documented here.
505 @end table
507 Calling @code{glob} will in most cases allocate resources which are used
508 to represent the result of the function call.  If the same object of
509 type @code{glob_t} is used in multiple call to @code{glob} the resources
510 are freed or reused so that no leaks appear.  But this does not include
511 the time when all @code{glob} calls are done.
513 @comment glob.h
514 @comment POSIX.2
515 @deftypefun void globfree (glob_t *@var{pglob})
516 The @code{globfree} function frees all resources allocated by previous
517 calls to @code{glob} associated with the object pointed to by
518 @var{pglob}.  This function should be called whenever the currently used
519 @code{glob_t} typed object isn't used anymore.
520 @end deftypefun
523 @node Regular Expressions
524 @section Regular Expression Matching
526 The GNU C library supports two interfaces for matching regular
527 expressions.  One is the standard POSIX.2 interface, and the other is
528 what the GNU system has had for many years.
530 Both interfaces are declared in the header file @file{regex.h}.
531 If you define @w{@code{_POSIX_C_SOURCE}}, then only the POSIX.2
532 functions, structures, and constants are declared.
533 @c !!! we only document the POSIX.2 interface here!!
535 @menu
536 * POSIX Regexp Compilation::    Using @code{regcomp} to prepare to match.
537 * Flags for POSIX Regexps::     Syntax variations for @code{regcomp}.
538 * Matching POSIX Regexps::      Using @code{regexec} to match the compiled
539                                    pattern that you get from @code{regcomp}.
540 * Regexp Subexpressions::       Finding which parts of the string were matched.
541 * Subexpression Complications:: Find points of which parts were matched.
542 * Regexp Cleanup::              Freeing storage; reporting errors.
543 @end menu
545 @node POSIX Regexp Compilation
546 @subsection POSIX Regular Expression Compilation
548 Before you can actually match a regular expression, you must
549 @dfn{compile} it.  This is not true compilation---it produces a special
550 data structure, not machine instructions.  But it is like ordinary
551 compilation in that its purpose is to enable you to ``execute'' the
552 pattern fast.  (@xref{Matching POSIX Regexps}, for how to use the
553 compiled regular expression for matching.)
555 There is a special data type for compiled regular expressions:
557 @comment regex.h
558 @comment POSIX.2
559 @deftp {Data Type} regex_t
560 This type of object holds a compiled regular expression.
561 It is actually a structure.  It has just one field that your programs
562 should look at:
564 @table @code
565 @item re_nsub
566 This field holds the number of parenthetical subexpressions in the
567 regular expression that was compiled.
568 @end table
570 There are several other fields, but we don't describe them here, because
571 only the functions in the library should use them.
572 @end deftp
574 After you create a @code{regex_t} object, you can compile a regular
575 expression into it by calling @code{regcomp}.
577 @comment regex.h
578 @comment POSIX.2
579 @deftypefun int regcomp (regex_t *@var{compiled}, const char *@var{pattern}, int @var{cflags})
580 The function @code{regcomp} ``compiles'' a regular expression into a
581 data structure that you can use with @code{regexec} to match against a
582 string.  The compiled regular expression format is designed for
583 efficient matching.  @code{regcomp} stores it into @code{*@var{compiled}}.
585 It's up to you to allocate an object of type @code{regex_t} and pass its
586 address to @code{regcomp}.
588 The argument @var{cflags} lets you specify various options that control
589 the syntax and semantics of regular expressions.  @xref{Flags for POSIX
590 Regexps}.
592 If you use the flag @code{REG_NOSUB}, then @code{regcomp} omits from
593 the compiled regular expression the information necessary to record
594 how subexpressions actually match.  In this case, you might as well
595 pass @code{0} for the @var{matchptr} and @var{nmatch} arguments when
596 you call @code{regexec}.
598 If you don't use @code{REG_NOSUB}, then the compiled regular expression
599 does have the capacity to record how subexpressions match.  Also,
600 @code{regcomp} tells you how many subexpressions @var{pattern} has, by
601 storing the number in @code{@var{compiled}->re_nsub}.  You can use that
602 value to decide how long an array to allocate to hold information about
603 subexpression matches.
605 @code{regcomp} returns @code{0} if it succeeds in compiling the regular
606 expression; otherwise, it returns a nonzero error code (see the table
607 below).  You can use @code{regerror} to produce an error message string
608 describing the reason for a nonzero value; see @ref{Regexp Cleanup}.
610 @end deftypefun
612 Here are the possible nonzero values that @code{regcomp} can return:
614 @table @code
615 @comment regex.h
616 @comment POSIX.2
617 @item REG_BADBR
618 There was an invalid @samp{\@{@dots{}\@}} construct in the regular
619 expression.  A valid @samp{\@{@dots{}\@}} construct must contain either
620 a single number, or two numbers in increasing order separated by a
621 comma.
623 @comment regex.h
624 @comment POSIX.2
625 @item REG_BADPAT
626 There was a syntax error in the regular expression.
628 @comment regex.h
629 @comment POSIX.2
630 @item REG_BADRPT
631 A repetition operator such as @samp{?} or @samp{*} appeared in a bad
632 position (with no preceding subexpression to act on).
634 @comment regex.h
635 @comment POSIX.2
636 @item REG_ECOLLATE
637 The regular expression referred to an invalid collating element (one not
638 defined in the current locale for string collation).  @xref{Locale
639 Categories}.
641 @comment regex.h
642 @comment POSIX.2
643 @item REG_ECTYPE
644 The regular expression referred to an invalid character class name.
646 @comment regex.h
647 @comment POSIX.2
648 @item REG_EESCAPE
649 The regular expression ended with @samp{\}.
651 @comment regex.h
652 @comment POSIX.2
653 @item REG_ESUBREG
654 There was an invalid number in the @samp{\@var{digit}} construct.
656 @comment regex.h
657 @comment POSIX.2
658 @item REG_EBRACK
659 There were unbalanced square brackets in the regular expression.
661 @comment regex.h
662 @comment POSIX.2
663 @item REG_EPAREN
664 An extended regular expression had unbalanced parentheses,
665 or a basic regular expression had unbalanced @samp{\(} and @samp{\)}.
667 @comment regex.h
668 @comment POSIX.2
669 @item REG_EBRACE
670 The regular expression had unbalanced @samp{\@{} and @samp{\@}}.
672 @comment regex.h
673 @comment POSIX.2
674 @item REG_ERANGE
675 One of the endpoints in a range expression was invalid.
677 @comment regex.h
678 @comment POSIX.2
679 @item REG_ESPACE
680 @code{regcomp} ran out of memory.
681 @end table
683 @node Flags for POSIX Regexps
684 @subsection Flags for POSIX Regular Expressions
686 These are the bit flags that you can use in the @var{cflags} operand when
687 compiling a regular expression with @code{regcomp}.
689 @table @code
690 @comment regex.h
691 @comment POSIX.2
692 @item REG_EXTENDED
693 Treat the pattern as an extended regular expression, rather than as a
694 basic regular expression.
696 @comment regex.h
697 @comment POSIX.2
698 @item REG_ICASE
699 Ignore case when matching letters.
701 @comment regex.h
702 @comment POSIX.2
703 @item REG_NOSUB
704 Don't bother storing the contents of the @var{matches-ptr} array.
706 @comment regex.h
707 @comment POSIX.2
708 @item REG_NEWLINE
709 Treat a newline in @var{string} as dividing @var{string} into multiple
710 lines, so that @samp{$} can match before the newline and @samp{^} can
711 match after.  Also, don't permit @samp{.} to match a newline, and don't
712 permit @samp{[^@dots{}]} to match a newline.
714 Otherwise, newline acts like any other ordinary character.
715 @end table
717 @node Matching POSIX Regexps
718 @subsection Matching a Compiled POSIX Regular Expression
720 Once you have compiled a regular expression, as described in @ref{POSIX
721 Regexp Compilation}, you can match it against strings using
722 @code{regexec}.  A match anywhere inside the string counts as success,
723 unless the regular expression contains anchor characters (@samp{^} or
724 @samp{$}).
726 @comment regex.h
727 @comment POSIX.2
728 @deftypefun int regexec (regex_t *@var{compiled}, char *@var{string}, size_t @var{nmatch}, regmatch_t @var{matchptr} @t{[]}, int @var{eflags})
729 This function tries to match the compiled regular expression
730 @code{*@var{compiled}} against @var{string}.
732 @code{regexec} returns @code{0} if the regular expression matches;
733 otherwise, it returns a nonzero value.  See the table below for
734 what nonzero values mean.  You can use @code{regerror} to produce an
735 error message string describing the reason for a nonzero value;
736 see @ref{Regexp Cleanup}.
738 The argument @var{eflags} is a word of bit flags that enable various
739 options.
741 If you want to get information about what part of @var{string} actually
742 matched the regular expression or its subexpressions, use the arguments
743 @var{matchptr} and @var{nmatch}.  Otherwise, pass @code{0} for
744 @var{nmatch}, and @code{NULL} for @var{matchptr}.  @xref{Regexp
745 Subexpressions}.
746 @end deftypefun
748 You must match the regular expression with the same set of current
749 locales that were in effect when you compiled the regular expression.
751 The function @code{regexec} accepts the following flags in the
752 @var{eflags} argument:
754 @table @code
755 @comment regex.h
756 @comment POSIX.2
757 @item REG_NOTBOL
758 Do not regard the beginning of the specified string as the beginning of
759 a line; more generally, don't make any assumptions about what text might
760 precede it.
762 @comment regex.h
763 @comment POSIX.2
764 @item REG_NOTEOL
765 Do not regard the end of the specified string as the end of a line; more
766 generally, don't make any assumptions about what text might follow it.
767 @end table
769 Here are the possible nonzero values that @code{regexec} can return:
771 @table @code
772 @comment regex.h
773 @comment POSIX.2
774 @item REG_NOMATCH
775 The pattern didn't match the string.  This isn't really an error.
777 @comment regex.h
778 @comment POSIX.2
779 @item REG_ESPACE
780 @code{regexec} ran out of memory.
781 @end table
783 @node Regexp Subexpressions
784 @subsection Match Results with Subexpressions
786 When @code{regexec} matches parenthetical subexpressions of
787 @var{pattern}, it records which parts of @var{string} they match.  It
788 returns that information by storing the offsets into an array whose
789 elements are structures of type @code{regmatch_t}.  The first element of
790 the array (index @code{0}) records the part of the string that matched
791 the entire regular expression.  Each other element of the array records
792 the beginning and end of the part that matched a single parenthetical
793 subexpression.
795 @comment regex.h
796 @comment POSIX.2
797 @deftp {Data Type} regmatch_t
798 This is the data type of the @var{matcharray} array that you pass to
799 @code{regexec}.  It contains two structure fields, as follows:
801 @table @code
802 @item rm_so
803 The offset in @var{string} of the beginning of a substring.  Add this
804 value to @var{string} to get the address of that part.
806 @item rm_eo
807 The offset in @var{string} of the end of the substring.
808 @end table
809 @end deftp
811 @comment regex.h
812 @comment POSIX.2
813 @deftp {Data Type} regoff_t
814 @code{regoff_t} is an alias for another signed integer type.
815 The fields of @code{regmatch_t} have type @code{regoff_t}.
816 @end deftp
818 The @code{regmatch_t} elements correspond to subexpressions
819 positionally; the first element (index @code{1}) records where the first
820 subexpression matched, the second element records the second
821 subexpression, and so on.  The order of the subexpressions is the order
822 in which they begin.
824 When you call @code{regexec}, you specify how long the @var{matchptr}
825 array is, with the @var{nmatch} argument.  This tells @code{regexec} how
826 many elements to store.  If the actual regular expression has more than
827 @var{nmatch} subexpressions, then you won't get offset information about
828 the rest of them.  But this doesn't alter whether the pattern matches a
829 particular string or not.
831 If you don't want @code{regexec} to return any information about where
832 the subexpressions matched, you can either supply @code{0} for
833 @var{nmatch}, or use the flag @code{REG_NOSUB} when you compile the
834 pattern with @code{regcomp}.
836 @node Subexpression Complications
837 @subsection Complications in Subexpression Matching
839 Sometimes a subexpression matches a substring of no characters.  This
840 happens when @samp{f\(o*\)} matches the string @samp{fum}.  (It really
841 matches just the @samp{f}.)  In this case, both of the offsets identify
842 the point in the string where the null substring was found.  In this
843 example, the offsets are both @code{1}.
845 Sometimes the entire regular expression can match without using some of
846 its subexpressions at all---for example, when @samp{ba\(na\)*} matches the
847 string @samp{ba}, the parenthetical subexpression is not used.  When
848 this happens, @code{regexec} stores @code{-1} in both fields of the
849 element for that subexpression.
851 Sometimes matching the entire regular expression can match a particular
852 subexpression more than once---for example, when @samp{ba\(na\)*}
853 matches the string @samp{bananana}, the parenthetical subexpression
854 matches three times.  When this happens, @code{regexec} usually stores
855 the offsets of the last part of the string that matched the
856 subexpression.  In the case of @samp{bananana}, these offsets are
857 @code{6} and @code{8}.
859 But the last match is not always the one that is chosen.  It's more
860 accurate to say that the last @emph{opportunity} to match is the one
861 that takes precedence.  What this means is that when one subexpression
862 appears within another, then the results reported for the inner
863 subexpression reflect whatever happened on the last match of the outer
864 subexpression.  For an example, consider @samp{\(ba\(na\)*s \)*} matching
865 the string @samp{bananas bas }.  The last time the inner expression
866 actually matches is near the end of the first word.  But it is
867 @emph{considered} again in the second word, and fails to match there.
868 @code{regexec} reports nonuse of the ``na'' subexpression.
870 Another place where this rule applies is when the regular expression
871 @smallexample
872 \(ba\(na\)*s \|nefer\(ti\)* \)*
873 @end smallexample
874 @noindent
875 matches @samp{bananas nefertiti}.  The ``na'' subexpression does match
876 in the first word, but it doesn't match in the second word because the
877 other alternative is used there.  Once again, the second repetition of
878 the outer subexpression overrides the first, and within that second
879 repetition, the ``na'' subexpression is not used.  So @code{regexec}
880 reports nonuse of the ``na'' subexpression.
882 @node Regexp Cleanup
883 @subsection POSIX Regexp Matching Cleanup
885 When you are finished using a compiled regular expression, you can
886 free the storage it uses by calling @code{regfree}.
888 @comment regex.h
889 @comment POSIX.2
890 @deftypefun void regfree (regex_t *@var{compiled})
891 Calling @code{regfree} frees all the storage that @code{*@var{compiled}}
892 points to.  This includes various internal fields of the @code{regex_t}
893 structure that aren't documented in this manual.
895 @code{regfree} does not free the object @code{*@var{compiled}} itself.
896 @end deftypefun
898 You should always free the space in a @code{regex_t} structure with
899 @code{regfree} before using the structure to compile another regular
900 expression.
902 When @code{regcomp} or @code{regexec} reports an error, you can use
903 the function @code{regerror} to turn it into an error message string.
905 @comment regex.h
906 @comment POSIX.2
907 @deftypefun size_t regerror (int @var{errcode}, regex_t *@var{compiled}, char *@var{buffer}, size_t @var{length})
908 This function produces an error message string for the error code
909 @var{errcode}, and stores the string in @var{length} bytes of memory
910 starting at @var{buffer}.  For the @var{compiled} argument, supply the
911 same compiled regular expression structure that @code{regcomp} or
912 @code{regexec} was working with when it got the error.  Alternatively,
913 you can supply @code{NULL} for @var{compiled}; you will still get a
914 meaningful error message, but it might not be as detailed.
916 If the error message can't fit in @var{length} bytes (including a
917 terminating null character), then @code{regerror} truncates it.
918 The string that @code{regerror} stores is always null-terminated
919 even if it has been truncated.
921 The return value of @code{regerror} is the minimum length needed to
922 store the entire error message.  If this is less than @var{length}, then
923 the error message was not truncated, and you can use it.  Otherwise, you
924 should call @code{regerror} again with a larger buffer.
926 Here is a function which uses @code{regerror}, but always dynamically
927 allocates a buffer for the error message:
929 @smallexample
930 char *get_regerror (int errcode, regex_t *compiled)
932   size_t length = regerror (errcode, compiled, NULL, 0);
933   char *buffer = xmalloc (length);
934   (void) regerror (errcode, compiled, buffer, length);
935   return buffer;
937 @end smallexample
938 @end deftypefun
940 @node Word Expansion
941 @section Shell-Style Word Expansion
942 @cindex word expansion
943 @cindex expansion of shell words
945 @dfn{Word expansion} means the process of splitting a string into
946 @dfn{words} and substituting for variables, commands, and wildcards
947 just as the shell does.
949 For example, when you write @samp{ls -l foo.c}, this string is split
950 into three separate words---@samp{ls}, @samp{-l} and @samp{foo.c}.
951 This is the most basic function of word expansion.
953 When you write @samp{ls *.c}, this can become many words, because
954 the word @samp{*.c} can be replaced with any number of file names.
955 This is called @dfn{wildcard expansion}, and it is also a part of
956 word expansion.
958 When you use @samp{echo $PATH} to print your path, you are taking
959 advantage of @dfn{variable substitution}, which is also part of word
960 expansion.
962 Ordinary programs can perform word expansion just like the shell by
963 calling the library function @code{wordexp}.
965 @menu
966 * Expansion Stages::            What word expansion does to a string.
967 * Calling Wordexp::             How to call @code{wordexp}.
968 * Flags for Wordexp::           Options you can enable in @code{wordexp}.
969 * Wordexp Example::             A sample program that does word expansion.
970 * Tilde Expansion::             Details of how tilde expansion works.
971 * Variable Substitution::       Different types of variable substitution.
972 @end menu
974 @node Expansion Stages
975 @subsection The Stages of Word Expansion
977 When word expansion is applied to a sequence of words, it performs the
978 following transformations in the order shown here:
980 @enumerate
981 @item
982 @cindex tilde expansion
983 @dfn{Tilde expansion}: Replacement of @samp{~foo} with the name of
984 the home directory of @samp{foo}.
986 @item
987 Next, three different transformations are applied in the same step,
988 from left to right:
990 @itemize @bullet
991 @item
992 @cindex variable substitution
993 @cindex substitution of variables and commands
994 @dfn{Variable substitution}: Environment variables are substituted for
995 references such as @samp{$foo}.
997 @item
998 @cindex command substitution
999 @dfn{Command substitution}: Constructs such as @w{@samp{`cat foo`}} and
1000 the equivalent @w{@samp{$(cat foo)}} are replaced with the output from
1001 the inner command.
1003 @item
1004 @cindex arithmetic expansion
1005 @dfn{Arithmetic expansion}: Constructs such as @samp{$(($x-1))} are
1006 replaced with the result of the arithmetic computation.
1007 @end itemize
1009 @item
1010 @cindex field splitting
1011 @dfn{Field splitting}: subdivision of the text into @dfn{words}.
1013 @item
1014 @cindex wildcard expansion
1015 @dfn{Wildcard expansion}: The replacement of a construct such as @samp{*.c}
1016 with a list of @samp{.c} file names.  Wildcard expansion applies to an
1017 entire word at a time, and replaces that word with 0 or more file names
1018 that are themselves words.
1020 @item
1021 @cindex quote removal
1022 @cindex removal of quotes
1023 @dfn{Quote removal}: The deletion of string-quotes, now that they have
1024 done their job by inhibiting the above transformations when appropriate.
1025 @end enumerate
1027 For the details of these transformations, and how to write the constructs
1028 that use them, see @w{@cite{The BASH Manual}} (to appear).
1030 @node Calling Wordexp
1031 @subsection Calling @code{wordexp}
1033 All the functions, constants and data types for word expansion are
1034 declared in the header file @file{wordexp.h}.
1036 Word expansion produces a vector of words (strings).  To return this
1037 vector, @code{wordexp} uses a special data type, @code{wordexp_t}, which
1038 is a structure.  You pass @code{wordexp} the address of the structure,
1039 and it fills in the structure's fields to tell you about the results.
1041 @comment wordexp.h
1042 @comment POSIX.2
1043 @deftp {Data Type} {wordexp_t}
1044 This data type holds a pointer to a word vector.  More precisely, it
1045 records both the address of the word vector and its size.
1047 @table @code
1048 @item we_wordc
1049 The number of elements in the vector.
1051 @item we_wordv
1052 The address of the vector.  This field has type @w{@code{char **}}.
1054 @item we_offs
1055 The offset of the first real element of the vector, from its nominal
1056 address in the @code{we_wordv} field.  Unlike the other fields, this
1057 is always an input to @code{wordexp}, rather than an output from it.
1059 If you use a nonzero offset, then that many elements at the beginning of
1060 the vector are left empty.  (The @code{wordexp} function fills them with
1061 null pointers.)
1063 The @code{we_offs} field is meaningful only if you use the
1064 @code{WRDE_DOOFFS} flag.  Otherwise, the offset is always zero
1065 regardless of what is in this field, and the first real element comes at
1066 the beginning of the vector.
1067 @end table
1068 @end deftp
1070 @comment wordexp.h
1071 @comment POSIX.2
1072 @deftypefun int wordexp (const char *@var{words}, wordexp_t *@var{word-vector-ptr}, int @var{flags})
1073 Perform word expansion on the string @var{words}, putting the result in
1074 a newly allocated vector, and store the size and address of this vector
1075 into @code{*@var{word-vector-ptr}}.  The argument @var{flags} is a
1076 combination of bit flags; see @ref{Flags for Wordexp}, for details of
1077 the flags.
1079 You shouldn't use any of the characters @samp{|&;<>} in the string
1080 @var{words} unless they are quoted; likewise for newline.  If you use
1081 these characters unquoted, you will get the @code{WRDE_BADCHAR} error
1082 code.  Don't use parentheses or braces unless they are quoted or part of
1083 a word expansion construct.  If you use quotation characters @samp{'"`},
1084 they should come in pairs that balance.
1086 The results of word expansion are a sequence of words.  The function
1087 @code{wordexp} allocates a string for each resulting word, then
1088 allocates a vector of type @code{char **} to store the addresses of
1089 these strings.  The last element of the vector is a null pointer.
1090 This vector is called the @dfn{word vector}.
1092 To return this vector, @code{wordexp} stores both its address and its
1093 length (number of elements, not counting the terminating null pointer)
1094 into @code{*@var{word-vector-ptr}}.
1096 If @code{wordexp} succeeds, it returns 0.  Otherwise, it returns one
1097 of these error codes:
1099 @table @code
1100 @comment wordexp.h
1101 @comment POSIX.2
1102 @item WRDE_BADCHAR
1103 The input string @var{words} contains an unquoted invalid character such
1104 as @samp{|}.
1106 @comment wordexp.h
1107 @comment POSIX.2
1108 @item WRDE_BADVAL
1109 The input string refers to an undefined shell variable, and you used the flag
1110 @code{WRDE_UNDEF} to forbid such references.
1112 @comment wordexp.h
1113 @comment POSIX.2
1114 @item WRDE_CMDSUB
1115 The input string uses command substitution, and you used the flag
1116 @code{WRDE_NOCMD} to forbid command substitution.
1118 @comment wordexp.h
1119 @comment POSIX.2
1120 @item WRDE_NOSPACE
1121 It was impossible to allocate memory to hold the result.  In this case,
1122 @code{wordexp} can store part of the results---as much as it could
1123 allocate room for.
1125 @comment wordexp.h
1126 @comment POSIX.2
1127 @item WRDE_SYNTAX
1128 There was a syntax error in the input string.  For example, an unmatched
1129 quoting character is a syntax error.
1130 @end table
1131 @end deftypefun
1133 @comment wordexp.h
1134 @comment POSIX.2
1135 @deftypefun void wordfree (wordexp_t *@var{word-vector-ptr})
1136 Free the storage used for the word-strings and vector that
1137 @code{*@var{word-vector-ptr}} points to.  This does not free the
1138 structure @code{*@var{word-vector-ptr}} itself---only the other
1139 data it points to.
1140 @end deftypefun
1142 @node Flags for Wordexp
1143 @subsection Flags for Word Expansion
1145 This section describes the flags that you can specify in the
1146 @var{flags} argument to @code{wordexp}.  Choose the flags you want,
1147 and combine them with the C operator @code{|}.
1149 @table @code
1150 @comment wordexp.h
1151 @comment POSIX.2
1152 @item WRDE_APPEND
1153 Append the words from this expansion to the vector of words produced by
1154 previous calls to @code{wordexp}.  This way you can effectively expand
1155 several words as if they were concatenated with spaces between them.
1157 In order for appending to work, you must not modify the contents of the
1158 word vector structure between calls to @code{wordexp}.  And, if you set
1159 @code{WRDE_DOOFFS} in the first call to @code{wordexp}, you must also
1160 set it when you append to the results.
1162 @comment wordexp.h
1163 @comment POSIX.2
1164 @item WRDE_DOOFFS
1165 Leave blank slots at the beginning of the vector of words.
1166 The @code{we_offs} field says how many slots to leave.
1167 The blank slots contain null pointers.
1169 @comment wordexp.h
1170 @comment POSIX.2
1171 @item WRDE_NOCMD
1172 Don't do command substitution; if the input requests command substitution,
1173 report an error.
1175 @comment wordexp.h
1176 @comment POSIX.2
1177 @item WRDE_REUSE
1178 Reuse a word vector made by a previous call to @code{wordexp}.
1179 Instead of allocating a new vector of words, this call to @code{wordexp}
1180 will use the vector that already exists (making it larger if necessary).
1182 Note that the vector may move, so it is not safe to save an old pointer
1183 and use it again after calling @code{wordexp}.  You must fetch
1184 @code{we_pathv} anew after each call.
1186 @comment wordexp.h
1187 @comment POSIX.2
1188 @item WRDE_SHOWERR
1189 Do show any error messages printed by commands run by command substitution.
1190 More precisely, allow these commands to inherit the standard error output
1191 stream of the current process.  By default, @code{wordexp} gives these
1192 commands a standard error stream that discards all output.
1194 @comment wordexp.h
1195 @comment POSIX.2
1196 @item WRDE_UNDEF
1197 If the input refers to a shell variable that is not defined, report an
1198 error.
1199 @end table
1201 @node Wordexp Example
1202 @subsection @code{wordexp} Example
1204 Here is an example of using @code{wordexp} to expand several strings
1205 and use the results to run a shell command.  It also shows the use of
1206 @code{WRDE_APPEND} to concatenate the expansions and of @code{wordfree}
1207 to free the space allocated by @code{wordexp}.
1209 @smallexample
1211 expand_and_execute (const char *program, const char *options)
1213   wordexp_t result;
1214   pid_t pid
1215   int status, i;
1217   /* @r{Expand the string for the program to run.}  */
1218   switch (wordexp (program, &result, 0))
1219     @{
1220     case 0:                     /* @r{Successful}.  */
1221       break;
1222     case WRDE_NOSPACE:
1223       /* @r{If the error was @code{WRDE_NOSPACE},}
1224          @r{then perhaps part of the result was allocated.}  */
1225       wordfree (&result);
1226     default:                    /* @r{Some other error.}  */
1227       return -1;
1228     @}
1230   /* @r{Expand the strings specified for the arguments.}  */
1231   for (i = 0; args[i]; i++)
1232     @{
1233       if (wordexp (options, &result, WRDE_APPEND))
1234         @{
1235           wordfree (&result);
1236           return -1;
1237         @}
1238     @}
1240   pid = fork ();
1241   if (pid == 0)
1242     @{
1243       /* @r{This is the child process.  Execute the command.} */
1244       execv (result.we_wordv[0], result.we_wordv);
1245       exit (EXIT_FAILURE);
1246     @}
1247   else if (pid < 0)
1248     /* @r{The fork failed.  Report failure.}  */
1249     status = -1;
1250   else
1251     /* @r{This is the parent process.  Wait for the child to complete.}  */
1252     if (waitpid (pid, &status, 0) != pid)
1253       status = -1;
1255   wordfree (&result);
1256   return status;
1258 @end smallexample
1260 @node Tilde Expansion
1261 @subsection Details of Tilde Expansion
1263 It's a standard part of shell syntax that you can use @samp{~} at the
1264 beginning of a file name to stand for your own home directory.  You
1265 can use @samp{~@var{user}} to stand for @var{user}'s home directory.
1267 @dfn{Tilde expansion} is the process of converting these abbreviations
1268 to the directory names that they stand for.
1270 Tilde expansion applies to the @samp{~} plus all following characters up
1271 to whitespace or a slash.  It takes place only at the beginning of a
1272 word, and only if none of the characters to be transformed is quoted in
1273 any way.
1275 Plain @samp{~} uses the value of the environment variable @code{HOME}
1276 as the proper home directory name.  @samp{~} followed by a user name
1277 uses @code{getpwname} to look up that user in the user database, and
1278 uses whatever directory is recorded there.  Thus, @samp{~} followed
1279 by your own name can give different results from plain @samp{~}, if
1280 the value of @code{HOME} is not really your home directory.
1282 @node Variable Substitution
1283 @subsection Details of Variable Substitution
1285 Part of ordinary shell syntax is the use of @samp{$@var{variable}} to
1286 substitute the value of a shell variable into a command.  This is called
1287 @dfn{variable substitution}, and it is one part of doing word expansion.
1289 There are two basic ways you can write a variable reference for
1290 substitution:
1292 @table @code
1293 @item $@{@var{variable}@}
1294 If you write braces around the variable name, then it is completely
1295 unambiguous where the variable name ends.  You can concatenate
1296 additional letters onto the end of the variable value by writing them
1297 immediately after the close brace.  For example, @samp{$@{foo@}s}
1298 expands into @samp{tractors}.
1300 @item $@var{variable}
1301 If you do not put braces around the variable name, then the variable
1302 name consists of all the alphanumeric characters and underscores that
1303 follow the @samp{$}.  The next punctuation character ends the variable
1304 name.  Thus, @samp{$foo-bar} refers to the variable @code{foo} and expands
1305 into @samp{tractor-bar}.
1306 @end table
1308 When you use braces, you can also use various constructs to modify the
1309 value that is substituted, or test it in various ways.
1311 @table @code
1312 @item $@{@var{variable}:-@var{default}@}
1313 Substitute the value of @var{variable}, but if that is empty or
1314 undefined, use @var{default} instead.
1316 @item $@{@var{variable}:=@var{default}@}
1317 Substitute the value of @var{variable}, but if that is empty or
1318 undefined, use @var{default} instead and set the variable to
1319 @var{default}.
1321 @item $@{@var{variable}:?@var{message}@}
1322 If @var{variable} is defined and not empty, substitute its value.
1324 Otherwise, print @var{message} as an error message on the standard error
1325 stream, and consider word expansion a failure.
1327 @c ??? How does wordexp report such an error?
1328 @c WRDE_BADVAL is returned.
1330 @item $@{@var{variable}:+@var{replacement}@}
1331 Substitute @var{replacement}, but only if @var{variable} is defined and
1332 nonempty.  Otherwise, substitute nothing for this construct.
1333 @end table
1335 @table @code
1336 @item $@{#@var{variable}@}
1337 Substitute a numeral which expresses in base ten the number of
1338 characters in the value of @var{variable}.  @samp{$@{#foo@}} stands for
1339 @samp{7}, because @samp{tractor} is seven characters.
1340 @end table
1342 These variants of variable substitution let you remove part of the
1343 variable's value before substituting it.  The @var{prefix} and
1344 @var{suffix} are not mere strings; they are wildcard patterns, just
1345 like the patterns that you use to match multiple file names.  But
1346 in this context, they match against parts of the variable value
1347 rather than against file names.
1349 @table @code
1350 @item $@{@var{variable}%%@var{suffix}@}
1351 Substitute the value of @var{variable}, but first discard from that
1352 variable any portion at the end that matches the pattern @var{suffix}.
1354 If there is more than one alternative for how to match against
1355 @var{suffix}, this construct uses the longest possible match.
1357 Thus, @samp{$@{foo%%r*@}} substitutes @samp{t}, because the largest
1358 match for @samp{r*} at the end of @samp{tractor} is @samp{ractor}.
1360 @item $@{@var{variable}%@var{suffix}@}
1361 Substitute the value of @var{variable}, but first discard from that
1362 variable any portion at the end that matches the pattern @var{suffix}.
1364 If there is more than one alternative for how to match against
1365 @var{suffix}, this construct uses the shortest possible alternative.
1367 Thus, @samp{$@{foo%%r*@}} substitutes @samp{tracto}, because the shortest
1368 match for @samp{r*} at the end of @samp{tractor} is just @samp{r}.
1370 @item $@{@var{variable}##@var{prefix}@}
1371 Substitute the value of @var{variable}, but first discard from that
1372 variable any portion at the beginning that matches the pattern @var{prefix}.
1374 If there is more than one alternative for how to match against
1375 @var{prefix}, this construct uses the longest possible match.
1377 Thus, @samp{$@{foo%%r*@}} substitutes @samp{t}, because the largest
1378 match for @samp{r*} at the end of @samp{tractor} is @samp{ractor}.
1380 @item $@{@var{variable}#@var{prefix}@}
1381 Substitute the value of @var{variable}, but first discard from that
1382 variable any portion at the beginning that matches the pattern @var{prefix}.
1384 If there is more than one alternative for how to match against
1385 @var{prefix}, this construct uses the shortest possible alternative.
1387 Thus, @samp{$@{foo%%r*@}} substitutes @samp{tracto}, because the shortest
1388 match for @samp{r*} at the end of @samp{tractor} is just @samp{r}.
1390 @end table