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