Imported from ../bash-2.05b.tar.gz.
[platform/upstream/bash.git] / doc / FAQ
1 This is the Bash FAQ, version 3.20, for Bash version 2.05b.
2
3 This document contains a set of frequently-asked questions concerning
4 Bash, the GNU Bourne-Again Shell.  Bash is a freely-available command
5 interpreter with advanced features for both interactive use and shell
6 programming.
7
8 Another good source of basic information about shells is the collection
9 of FAQ articles periodically posted to comp.unix.shell.
10
11 Questions and comments concerning this document should be sent to
12 chet@po.cwru.edu.
13
14 This document is available for anonymous FTP with the URL
15
16 ftp://ftp.cwru.edu/pub/bash/FAQ
17
18 The Bash home page is http://cnswww.cns.cwru.edu/~chet/bash/bashtop.html
19
20 ----------
21 Contents:
22
23 Section A:  The Basics
24
25 A1) What is it?
26 A2) What's the latest version?
27 A3) Where can I get it?
28 A4) On what machines will bash run?
29 A5) Will bash run on operating systems other than Unix?
30 A6) How can I build bash with gcc?
31 A7) How can I make bash my login shell?
32 A8) I just changed my login shell to bash, and now I can't FTP into my
33     machine.  Why not?
34 A9) What's the `POSIX 1003.2 standard'?
35 A10) What is the bash `posix mode'?
36
37 Section B:  The latest version
38
39 B1) What's new in version 2.05b?
40 B2) Are there any user-visible incompatibilities between bash-2.05b and
41     bash-1.14.7?
42
43 Section C:  Differences from other Unix shells
44
45 C1) How does bash differ from sh, the Bourne shell?
46 C2) How does bash differ from the Korn shell, version ksh88?
47 C3) Which new features in ksh-93 are not in bash, and which are?
48
49 Section D:  Why does bash do some things differently than other Unix shells?
50
51 D1) Why does bash run a different version of `command' than
52     `which command' says it will?
53 D2) Why doesn't bash treat brace expansions exactly like csh?
54 D3) Why doesn't bash have csh variable modifiers?
55 D4) How can I make my csh aliases work when I convert to bash?
56 D5) How can I pipe standard output and standard error from one command to
57     another, like csh does with `|&'?
58 D6) Now that I've converted from ksh to bash, are there equivalents to
59     ksh features like autoloaded functions and the `whence' command?
60
61 Section E:  Why does bash do certain things the way it does?
62
63 E1) Why is the bash builtin `test' slightly different from /bin/test?
64 E2) Why does bash sometimes say `Broken pipe'?
65 E3) When I have terminal escape sequences in my prompt, why does bash
66     wrap lines at the wrong column?
67 E4) If I pipe the output of a command into `read variable', why doesn't
68     the output show up in $variable when the read command finishes?
69 E5) I have a bunch of shell scripts that use backslash-escaped characters
70     in arguments to `echo'.  Bash doesn't interpret these characters.  Why
71     not, and how can I make it understand them?
72 E6) Why doesn't a while or for loop get suspended when I type ^Z?
73 E7) What about empty for loops in Makefiles?
74 E8) Why does the arithmetic evaluation code complain about `08'?
75 E9) Why does the pattern matching expression [A-Z]* match files beginning
76     with every letter except `z'?
77 E10) Why does `cd //' leave $PWD as `//'?
78
79 Section F:  Things to watch out for on certain Unix versions
80
81 F1) Why can't I use command line editing in my `cmdtool'?
82 F2) I built bash on Solaris 2.  Why do globbing expansions and filename
83     completion chop off the first few characters of each filename?
84 F3) Why does bash dump core after I interrupt username completion or
85     `~user' tilde expansion on a machine running NIS?
86 F4) I'm running SVR4.2.  Why is the line erased every time I type `@'?
87 F5) Why does bash report syntax errors when my C News scripts use a
88     redirection before a subshell command?
89 F6) Why can't I use vi-mode editing on Red Hat Linux 6.1?
90 F7) Why do bash-2.05a and  bash-2.05b fail to compile `printf.def' on
91     HP/UX 11.x?
92
93 Section G:  How can I get bash to do certain common things?
94
95 G1) How can I get bash to read and display eight-bit characters?
96 G2) How do I write a function `x' to replace builtin command `x', but
97     still invoke the command from within the function?
98 G3) How can I find the value of a shell variable whose name is the value
99     of another shell variable?
100 G4) How can I make the bash `time' reserved word print timing output that
101     looks like the output from my system's /usr/bin/time?
102 G5) How do I get the current directory into my prompt?
103 G6) How can I rename "*.foo" to "*.bar"?
104 G7) How can I translate a filename from uppercase to lowercase?
105 G8) How can I write a filename expansion (globbing) pattern that will match
106     all files in the current directory except "." and ".."?
107
108 Section H:  Where do I go from here?
109
110 H1) How do I report bugs in bash, and where should I look for fixes and
111     advice?
112 H2) What kind of bash documentation is there?
113 H3) What's coming in future versions?
114 H4) What's on the bash `wish list'?
115 H5) When will the next release appear?
116
117 ----------
118 Section A:  The Basics
119
120 A1)  What is it?
121
122 Bash is a Unix command interpreter (shell).  It is an implementation of
123 the Posix 1003.2 shell standard, and resembles the Korn and System V
124 shells.
125
126 Bash contains a number of enhancements over those shells, both
127 for interactive use and shell programming.  Features geared
128 toward interactive use include command line editing, command
129 history, job control, aliases, and prompt expansion.  Programming
130 features include additional variable expansions, shell
131 arithmetic, and a number of variables and options to control
132 shell behavior.
133
134 Bash was originally written by Brian Fox of the Free Software
135 Foundation.  The current developer and maintainer is Chet Ramey
136 of Case Western Reserve University.
137
138 A2)  What's the latest version?
139
140 The latest version is 2.05b, first made available on Wednesday, 17
141 July, 2002.
142
143 A3)  Where can I get it?
144
145 Bash is the GNU project's shell, and so is available from the
146 master GNU archive site, ftp.gnu.org, and its mirrors.  The
147 latest version is also available for FTP from ftp.cwru.edu.
148 The following URLs tell how to get version 2.05b:
149
150 ftp://ftp.gnu.org/pub/gnu/bash/bash-2.05b.tar.gz
151 ftp://ftp.cwru.edu/pub/bash/bash-2.05b.tar.gz
152
153 Formatted versions of the documentation are available with the URLs:
154
155 ftp://ftp.gnu.org/pub/gnu/bash/bash-doc-2.05b.tar.gz
156 ftp://ftp.cwru.edu/pub/bash/bash-doc-2.05b.tar.gz
157
158 A4)  On what machines will bash run?
159
160 Bash has been ported to nearly every version of UNIX.  All you
161 should have to do to build it on a machine for which a port
162 exists is to type `configure' and then `make'.  The build process
163 will attempt to discover the version of UNIX you have and tailor
164 itself accordingly, using a script created by GNU autoconf.
165
166 More information appears in the file `INSTALL' in the distribution.
167
168 The Bash web page (http://cnswww.cns.cwru.edu/~chet/bash/bashtop.html)
169 explains how to obtain binary versions of bash for most of the major
170 commercial Unix systems.
171
172 A5) Will bash run on operating systems other than Unix?
173
174 Configuration specifics for Unix-like systems such as QNX and
175 LynxOS are included in the distribution.  Bash-2.05 and later
176 versions should compile and run on Minix 2.0 (patches were
177 contributed), but I don't believe anyone has built bash-2.x on
178 earlier Minix versions yet. 
179
180 Bash has been ported to versions of Windows implementing the Win32
181 programming interface.  This includes Windows 95 and Windows NT.
182 The port was done by Cygnus Solutions as part of their CYGWIN
183 project.  For more information about the project, look at the URLs
184
185 http://www.cygwin.com/
186 http://sourceware.cygnus.com/cygwin
187
188 Cygnus originally ported bash-1.14.7, and that port was part of their
189 early GNU-Win32 (the original name) releases.  Cygnus has also done a
190 port of bash-2.05 to the CYGWIN environment, and it is available as
191 part of their current release.
192
193 Bash-2.05b should require no local Cygnus changes to build and run under
194 CYGWIN.
195
196 The Cygnus port works only on Intel machines.  There is a port of bash
197 (I don't know which version) to the alpha/NT environment available from
198
199 ftp://ftp.gnustep.org//pub/win32/bash-alpha-nt-1.01.tar.gz
200
201 DJ Delorie has a port of bash-2.x which runs under MS-DOS, as part
202 of the DJGPP project.  For more information on the project, see
203
204 http://www.delorie.com/djgpp/
205
206 I have been told that the original DJGPP port was done by Daisuke Aoyama.
207
208 Mark Elbrecht <snowball3@bigfoot.com> has sent me notice that bash-2.04
209 is available for DJGPP V2.  The files are available as:
210
211 ftp://ftp.simtel.net/pub/simtelnet/gnu/djgpp/v2gnu/bsh204b.zip  binary
212 ftp://ftp.simtel.net/pub/simtelnet/gnu/djgpp/v2gnu/bsh204d.zip  documentation
213 ftp://ftp.simtel.net/pub/simtelnet/gnu/djgpp/v2gnu/bsh204s.zip  source
214
215 Mark has begun to work with bash-2.05, but I don't know the status.
216
217 Ports of bash-1.12 and bash-2.0 are available for OS/2 from
218
219 ftp://hobbes.nmsu.edu/pub/os2/util/shell/bash_112.zip
220 ftp://hobbes.nmsu.edu/pub/os2/util/shell/bash-2.0(253).zip
221
222 I haven't looked at either, but the second appears to be a binary-only
223 distribution.  Beware.
224
225 I have received word that Bash (I'm not sure which version, but I
226 believe that it's at least bash-2.02.1) is the standard shell on
227 BeOS.
228
229 A6) How can I build bash with gcc? 
230
231 Bash configures to use gcc by default if it is available.  Read the
232 file INSTALL in the distribution for more information.
233
234 A7)  How can I make bash my login shell?
235
236 Some machines let you use `chsh' to change your login shell.  Other
237 systems use `passwd -s' or `passwd -e'.  If one of these works for
238 you, that's all you need.  Note that many systems require the full
239 pathname to a shell to appear in /etc/shells before you can make it
240 your login shell.  For this, you may need the assistance of your
241 friendly local system administrator. 
242
243 If you cannot do this, you can still use bash as your login shell, but
244 you need to perform some tricks.  The basic idea is to add a command
245 to your login shell's startup file to replace your login shell with
246 bash.
247
248 For example, if your login shell is csh or tcsh, and you have installed
249 bash in /usr/gnu/bin/bash, add the following line to ~/.login:
250
251         if ( -f /usr/gnu/bin/bash ) exec /usr/gnu/bin/bash --login
252
253 (the `--login' tells bash that it is a login shell).
254
255 It's not a good idea to put this command into ~/.cshrc, because every
256 csh you run without the `-f' option, even ones started to run csh scripts,
257 reads that file.  If you must put the command in ~/.cshrc, use something
258 like
259
260         if ( $?prompt ) exec /usr/gnu/bin/bash --login
261
262 to ensure that bash is exec'd only when the csh is interactive.
263
264 If your login shell is sh or ksh, you have to do two things.
265
266 First, create an empty file in your home directory named `.bash_profile'.
267 The existence of this file will prevent the exec'd bash from trying to
268 read ~/.profile, and re-execing itself over and over again.  ~/.bash_profile
269 is the first file bash tries to read initialization commands from when
270 it is invoked as a login shell.
271
272 Next, add a line similar to the above to ~/.profile:
273
274         [ -f /usr/gnu/bin/bash ] && exec /usr/gnu/bin/bash --login
275
276 This will cause login shells to replace themselves with bash running as
277 a login shell.  Once you have this working, you can copy your initialization
278 code from ~/.profile to ~/.bash_profile.
279
280 I have received word that the recipe supplied above is insufficient for
281 machines running CDE.  CDE has a maze of twisty little startup files, all
282 slightly different.
283
284 If you cannot change your login shell in the password file to bash, you
285 will have to (apparently) live with CDE using the shell in the password
286 file to run its startup scripts.  If you have changed your shell to bash,
287 there is code in the CDE startup files (on Solaris, at least) that attempts
288 to do the right thing.  It is, however, often broken, and may require that
289 you use the $BASH_ENV trick described below.
290
291 `dtterm' claims to use $SHELL as the default program to start, so if you
292 can change $SHELL in the CDE startup files, you should be able to use bash
293 in your terminal windows.
294
295 Setting DTSOURCEPROFILE in ~/.dtprofile will cause the `Xsession' program
296 to read your login shell's startup files.  You may be able to use bash for
297 the rest of the CDE programs by setting SHELL to bash in ~/.dtprofile as
298 well, but I have not tried this.
299
300 You can use the above `exec' recipe to start bash when not logging in with
301 CDE by testing the value of the DT variable:
302
303         if [ -n "$DT" ]; then
304                 [ -f /usr/gnu/bin/bash ] && exec /usr/gnu/bin/bash --login
305         fi
306
307 If CDE starts its shells non-interactively during login, the login shell
308 startup files (~/.profile, ~/.bash_profile) will not be sourced at login.
309 To get around this problem, append a line similar to the following to your
310 ~/.dtprofile:
311
312         BASH_ENV=${HOME}/.bash_profile ; export BASH_ENV
313
314 and add the following line to the beginning of ~/.bash_profile:
315
316         unset BASH_ENV
317
318 A8) I just changed my login shell to bash, and now I can't FTP into my
319    machine.  Why not?
320
321 You must add the full pathname to bash to the file /etc/shells.  As
322 noted in the answer to the previous question, many systems require
323 this before you can make bash your login shell. 
324
325 Most versions of ftpd use this file to prohibit `special' users
326 such as `uucp' and `news' from using FTP. 
327
328 A9)  What's the `POSIX 1003.2 standard'?
329
330 POSIX is a name originally coined by Richard Stallman for a
331 family of open system standards based on UNIX.  There are a
332 number of aspects of UNIX under consideration for
333 standardization, from the basic system services at the system
334 call and C library level to applications and tools to system
335 administration and management.  Each area of standardization is
336 assigned to a working group in the 1003 series. 
337
338 The POSIX Shell and Utilities standard has been developed by IEEE
339 Working Group 1003.2 (POSIX.2).  It concentrates on the command
340 interpreter interface and utility programs commonly executed from
341 the command line or by other programs.  An initial version of the
342 standard has been approved and published by the IEEE, and work is
343 currently underway to update it. 
344
345 Bash is concerned with the aspects of the shell's behavior
346 defined by POSIX.2.  The shell command language has of course
347 been standardized, including the basic flow control and program
348 execution constructs, I/O redirection and pipelining, argument
349 handling, variable expansion, and quoting. 
350
351 The `special' builtins, which must be implemented as part of the
352 shell to provide the desired functionality, are specified as
353 being part of the shell; examples of these are `eval' and
354 `export'.  Other utilities appear in the sections of POSIX.2 not
355 devoted to the shell which are commonly (and in some cases must
356 be) implemented as builtin commands, such as `read' and `test'. 
357 POSIX.2 also specifies aspects of the shell's interactive
358 behavior as part of the UPE, including job control and command
359 line editing.  Only vi-style line editing commands have been
360 standardized; emacs editing commands were left out due to
361 objections.
362
363 The Open Group has made an older version of its Single Unix
364 Specification (version 2), which is very similar to POSIX.2,
365 available on the web at
366
367 http://www.opengroup.org/onlinepubs/007908799/
368
369 The Single Unix Specification, version 3, is available on the web at
370
371 http://www.opengroup.org/onlinepubs/007904975/
372
373 A10)  What is the bash `posix mode'?
374
375 Although bash is an implementation of the POSIX.2 shell
376 specification, there are areas where the bash default behavior
377 differs from that spec.  The bash `posix mode' changes the bash
378 behavior in these areas so that it obeys the spec more closely. 
379
380 Posix mode is entered by starting bash with the --posix or
381 '-o posix' option or executing `set -o posix' after bash is running.
382
383 The specific aspects of bash which change when posix mode is
384 active are listed in the file POSIX in the bash distribution.
385 They are also listed in a section in the Bash Reference Manual
386 (from which that file is generated).
387
388 Section B:  The latest version
389
390 B1) What's new in version 2.05b?
391
392 The raison d'etre for bash-2.05b is to make a second intermediate
393 release containing the first of the new features to be available
394 in bash-3.0 and get feedback on those features before proceeding.
395 The major new feature is multibyte character support in both Bash
396 and Readline.
397
398 Bash-2.05b contains the following new features (see the manual page for
399 complete descriptions and the CHANGES and NEWS files in the bash-2.05b
400 distribution):
401
402 o support for multibyte characters has been added to both bash and readline
403
404 o the DEBUG trap is now run *before* simple commands, ((...)) commands,
405   [[...]] conditional commands, and for ((...)) loops
406
407 o the shell now performs arithmetic in the largest integer size the machine
408   supports (intmax_t)
409
410 o there is a new \D{...} prompt expansion; passes the `...' to strftime(3)
411   and inserts the result into the expanded prompt
412
413 o there is a new `here-string' redirection operator:  <<< word
414
415 o when displaying variables, function attributes and definitions are shown
416   separately, allowing them to be re-used as input (attempting to re-use
417   the old output would result in syntax errors).
418
419 o `read' has a new `-u fd' option to read from a specified file descriptor
420
421 o the bash debugger in examples/bashdb has been modified to work with the
422   new DEBUG trap semantics, the command set has been made more gdb-like,
423   and the changes to $LINENO make debugging functions work better
424
425 o the expansion of $LINENO inside a shell function is only relative to the
426   function start if the shell is interactive -- if the shell is running a
427   script, $LINENO expands to the line number in the script.  This is as
428   POSIX-2001 requires
429
430
431 A short feature history dating from Bash-2.0:
432
433 Bash-2.05a introduced the following new features:
434
435 o The `printf' builtin has undergone major work
436
437 o There is a new read-only `shopt' option: login_shell, which is set by
438   login shells and unset otherwise
439
440 o New `\A' prompt string escape sequence; expanding to time in 24-hour
441   HH:MM format
442
443 o New `-A group/-g' option to complete and compgen; goes group name
444   completion
445
446 o New [+-]O invocation option to set and unset `shopt' options at startup
447
448 o ksh-like `ERR' trap
449
450 o `for' loops now allow empty word lists after the `in' reserved word
451
452 o new `hard' and `soft' arguments for the `ulimit' builtin
453
454 o Readline can be configured to place the user at the same point on the line
455   when retrieving commands from the history list
456
457 o Readline can be configured to skip `hidden' files (filenames with a leading
458   `.' on Unix) when performing completion
459
460 Bash-2.05 introduced the following new features:
461
462 o This version has once again reverted to using locales and strcoll(3) when
463   processing pattern matching bracket expressions, as POSIX requires. 
464 o Added a new `--init-file' invocation argument as a synonym for `--rcfile',
465   per the new GNU coding standards.
466 o The /dev/tcp and /dev/udp redirections now accept service names as well as
467   port numbers.
468 o `complete' and `compgen' now take a `-o value' option, which controls some
469    of the aspects of that compspec.  Valid values are:
470
471         default - perform bash default completion if programmable
472                   completion produces no matches
473         dirnames - perform directory name completion if programmable
474                    completion produces no matches
475         filenames - tell readline that the compspec produces filenames,
476                     so it can do things like append slashes to
477                     directory names and suppress trailing spaces
478 o A new loadable builtin, realpath, which canonicalizes and expands symlinks
479   in pathname arguments.
480 o When `set' is called without options, it prints function defintions in a
481   way that allows them to be reused as input.  This affects `declare' and 
482   `declare -p' as well.  This only happens when the shell is not in POSIX
483    mode, since POSIX.2 forbids this behavior.
484
485 Bash-2.04 introduced the following new features:
486
487 o Programmable word completion with the new `complete' and `compgen' builtins;
488   examples are provided in examples/complete/complete-examples
489 o `history' has a new `-d' option to delete a history entry
490 o `bind' has a new `-x' option to bind key sequences to shell commands
491 o The prompt expansion code has new `\j' and `\l' escape sequences
492 o The `no_empty_cmd_completion' shell option, if enabled, inhibits
493   command completion when TAB is typed on an empty line
494 o `help' has a new `-s' option to print a usage synopsis
495 o New arithmetic operators: var++, var--, ++var, --var, expr1,expr2 (comma)
496 o New ksh93-style arithmetic for command:
497         for ((expr1 ; expr2; expr3 )); do list; done
498 o `read' has new options: `-t', `-n', `-d', `-s'
499 o The redirection code handles several filenames specially:  /dev/fd/N,
500   /dev/stdin, /dev/stdout, /dev/stderr
501 o The redirection code now recognizes /dev/tcp/HOST/PORT and
502   /dev/udp/HOST/PORT and tries to open a TCP or UDP socket, respectively,
503   to the specified port on the specified host
504 o The ${!prefix*} expansion has been implemented
505 o A new FUNCNAME variable, which expands to the name of a currently-executing
506   function
507 o The GROUPS variable is no longer readonly
508 o A new shopt `xpg_echo' variable, to control the behavior of echo with
509   respect to backslash-escape sequences at runtime
510 o The NON_INTERACTIVE_LOGIN_SHELLS #define has returned
511
512 The version of Readline released with Bash-2.04, Readline-4.1, had several
513 new features as well:
514
515 o Parentheses matching is always compiled into readline, and controllable
516   with the new `blink-matching-paren' variable
517 o The history-search-forward and history-search-backward functions now leave
518   point at the end of the line when the search string is empty, like
519   reverse-search-history, and forward-search-history
520 o A new function for applications:  rl_on_new_line_with_prompt()
521 o New variables for applications:  rl_already_prompted, and rl_gnu_readline_p
522
523
524 Bash-2.03 had very few new features, in keeping with the convention
525 that odd-numbered releases provide mainly bug fixes.  A number of new
526 features were added to Readline, mostly at the request of the Cygnus
527 folks.
528
529 A new shopt option, `restricted_shell', so that startup files can test
530         whether or not the shell was started in restricted mode
531 Filename generation is now performed on the words between ( and ) in
532         compound array assignments (this is really a bug fix)
533 OLDPWD is now auto-exported, as POSIX.2 requires
534 ENV and BASH_ENV are read-only variables in a restricted shell
535 Bash may now be linked against an already-installed Readline library,
536         as long as the Readline library is version 4 or newer
537 All shells begun with the `--login' option will source the login shell
538         startup files, even if the shell is not interactive
539
540 There were lots of changes to the version of the Readline library released
541 along with Bash-2.03.  For a complete list of the changes, read the file
542 CHANGES in the Bash-2.03 distribution.
543
544 Bash-2.02 contained the following new features:
545
546 a new version of malloc (based on the old GNU malloc code in previous
547         bash versions) that is more page-oriented, more conservative
548         with memory usage, does not `orphan' large blocks when they
549         are freed, is usable on 64-bit machines, and has allocation
550         checking turned on unconditionally
551 POSIX.2-style globbing character classes ([:alpha:], [:alnum:], etc.)
552 POSIX.2-style globbing equivalence classes
553 POSIX.2-style globbing collating symbols
554 the ksh [[...]] extended conditional command
555 the ksh egrep-style extended pattern matching operators
556 a new `printf' builtin
557 the ksh-like $(<filename) command substitution, which is equivalent to
558         $(cat filename)
559 new tilde prefixes that expand to directories from the directory stack
560 new `**' arithmetic operator to do exponentiation
561 case-insensitive globbing (filename expansion)
562 menu completion a la tcsh
563 `magic-space' history expansion function like tcsh
564 the readline inputrc `language' has a new file inclusion directive ($include)
565
566 Bash-2.01 contained only a few new features:
567
568 new `GROUPS' builtin array variable containing the user's group list
569 new bindable readline commands: history-and-alias-expand-line and
570         alias-expand-line
571
572 Bash-2.0 contained extensive changes and new features from bash-1.14.7.
573 Here's a short list:
574
575 new `time' reserved word to time pipelines, shell builtins, and
576         shell functions
577 one-dimensional arrays with a new compound assignment statement,
578         appropriate expansion constructs and modifications to some
579         of the builtins (read, declare, etc.) to use them
580 new quoting syntaxes for ANSI-C string expansion and locale-specific
581         string translation
582 new expansions to do substring extraction, pattern replacement, and
583         indirect variable expansion
584 new builtins: `disown' and `shopt'
585 new variables: HISTIGNORE, SHELLOPTS, PIPESTATUS, DIRSTACK, GLOBIGNORE,
586                MACHTYPE, BASH_VERSINFO
587 special handling of many unused or redundant variables removed
588         (e.g., $notify, $glob_dot_filenames, $no_exit_on_failed_exec)
589 dynamic loading of new builtin commands; many loadable examples provided
590 new prompt expansions: \a, \e, \n, \H, \T, \@, \v, \V
591 history and aliases available in shell scripts
592 new readline variables: enable-keypad, mark-directories, input-meta,
593         visible-stats, disable-completion, comment-begin
594 new readline commands to manipulate the mark and operate on the region
595 new readline emacs mode commands and bindings for ksh-88 compatibility
596 updated and extended builtins
597 new DEBUG trap
598 expanded (and now documented) restricted shell mode
599
600 implementation stuff:   
601 autoconf-based configuration
602 nearly all of the bugs reported since version 1.14 have been fixed
603 most builtins converted to use builtin `getopt' for consistency
604 most builtins use -p option to display output in a reusable form
605         (for consistency)
606 grammar tighter and smaller (66 reduce-reduce conflicts gone)
607 lots of code now smaller and faster
608 test suite greatly expanded
609
610 B2) Are there any user-visible incompatibilities between bash-2.05b and
611     bash-1.14.7?
612
613 There are a few incompatibilities between version 1.14.7 and version 2.05b.
614 They are detailed in the file COMPAT in the bash distribution.  That file
615 is not meant to be all-encompassing; send mail to bash-maintainers@gnu.org
616 if if you find something that's not mentioned there.
617
618 Section C:  Differences from other Unix shells
619
620 C1) How does bash differ from sh, the Bourne shell?
621
622 This is a non-comprehensive list of features that differentiate bash
623 from the SVR4.2 shell.  The bash manual page explains these more
624 completely.
625
626 Things bash has that sh does not:
627         long invocation options
628         [+-]O invocation option
629         -l invocation option
630         `!' reserved word to invert pipeline return value
631         `time' reserved word to time pipelines and shell builtins
632         the `function' reserved word
633         the `select' compound command and reserved word
634         arithmetic for command: for ((expr1 ; expr2; expr3 )); do list; done
635         new $'...' and $"..." quoting
636         the $(...) form of command substitution
637         the $(<filename) form of command substitution, equivalent to
638                 $(cat filename)
639         the ${#param} parameter value length operator
640         the ${!param} indirect parameter expansion operator
641         the ${!param*} prefix expansion operator
642         the ${param:offset[:length]} parameter substring operator
643         the ${param/pat[/string]} parameter pattern substitution operator
644         expansions to perform substring removal (${p%[%]w}, ${p#[#]w})
645         expansion of positional parameters beyond $9 with ${num}
646         variables: BASH, BASH_VERSION, BASH_VERSINFO, UID, EUID, REPLY,
647                    TIMEFORMAT, PPID, PWD, OLDPWD, SHLVL, RANDOM, SECONDS,
648                    LINENO, HISTCMD, HOSTTYPE, OSTYPE, MACHTYPE, HOSTNAME,
649                    ENV, PS3, PS4, DIRSTACK, PIPESTATUS, HISTSIZE, HISTFILE,
650                    HISTFILESIZE, HISTCONTROL, HISTIGNORE, GLOBIGNORE, GROUPS,
651                    PROMPT_COMMAND, FCEDIT, FIGNORE, IGNOREEOF, INPUTRC,
652                    SHELLOPTS, OPTERR, HOSTFILE, TMOUT, FUNCNAME, histchars,
653                    auto_resume
654         DEBUG trap
655         ERR trap
656         variable arrays with new compound assignment syntax
657         redirections: <>, &>, >|, <<<, [n]<&word-, [n]>&word-
658         prompt string special char translation and variable expansion
659         auto-export of variables in initial environment
660         command search finds functions before builtins
661         bash return builtin will exit a file sourced with `.'
662         builtins: cd -/-L/-P, exec -l/-c/-a, echo -e/-E, hash -d/-l/-p/-t.
663                   export -n/-f/-p/name=value, pwd -L/-P,
664                   read -e/-p/-a/-t/-n/-d/-s/-u,
665                   readonly -a/-f/name=value, trap -l, set +o,
666                   set -b/-m/-o option/-h/-p/-B/-C/-H/-P,
667                   unset -f/-v, ulimit -m/-p/-u,
668                   type -a/-p/-t/-f/-P, suspend -f, kill -n,
669                   test -o optname/s1 == s2/s1 < s2/s1 > s2/-nt/-ot/-ef/-O/-G/-S
670         bash reads ~/.bashrc for interactive shells, $ENV for non-interactive
671         bash restricted shell mode is more extensive
672         bash allows functions and variables with the same name
673         brace expansion
674         tilde expansion
675         arithmetic expansion with $((...)) and `let' builtin
676         the `[[...]]' extended conditional command
677         process substitution
678         aliases and alias/unalias builtins
679         local variables in functions and `local' builtin
680         readline and command-line editing with programmable completion
681         command history and history/fc builtins
682         csh-like history expansion
683         other new bash builtins: bind, command, compgen, complete, builtin,
684                                  declare/typeset, dirs, enable, fc, help,
685                                  history, logout, popd, pushd, disown, shopt,
686                                  printf
687         exported functions
688         filename generation when using output redirection (command >a*)
689         POSIX.2-style globbing character classes
690         POSIX.2-style globbing equivalence classes
691         POSIX.2-style globbing collating symbols
692         egrep-like extended pattern matching operators
693         case-insensitive pattern matching and globbing
694         variable assignments preceding commands affect only that command,
695                 even for builtins and functions
696         posix mode
697         redirection to /dev/fd/N, /dev/stdin, /dev/stdout, /dev/stderr,
698                 /dev/tcp/host/port, /dev/udp/host/port
699
700 Things sh has that bash does not:
701         uses variable SHACCT to do shell accounting
702         includes `stop' builtin (bash can use alias stop='kill -s STOP')
703         `newgrp' builtin
704         turns on job control if called as `jsh'
705         $TIMEOUT (like bash $TMOUT)
706         `^' is a synonym for `|'
707         new SVR4.2 sh builtins: mldmode, priv
708
709 Implementation differences:
710         redirection to/from compound commands causes sh to create a subshell
711         bash does not allow unbalanced quotes; sh silently inserts them at EOF
712         bash does not mess with signal 11
713         sh sets (euid, egid) to (uid, gid) if -p not supplied and uid < 100
714         bash splits only the results of expansions on IFS, using POSIX.2
715                 field splitting rules; sh splits all words on IFS
716         sh does not allow MAILCHECK to be unset (?)
717         sh does not allow traps on SIGALRM or SIGCHLD
718         bash allows multiple option arguments when invoked (e.g. -x -v);
719                 sh allows only a single option argument (`sh -x -v' attempts
720                 to open a file named `-v', and, on SunOS 4.1.4, dumps core.
721                 On Solaris 2.4 and earlier versions, sh goes into an infinite
722                 loop.)
723         sh exits a script if any builtin fails; bash exits only if one of
724                 the POSIX.2 `special' builtins fails
725
726 C2)  How does bash differ from the Korn shell, version ksh88?
727
728 Things bash has or uses that ksh88 does not:
729         long invocation options
730         [-+]O invocation option
731         -l invocation option
732         `!' reserved word
733         arithmetic for command: for ((expr1 ; expr2; expr3 )); do list; done
734         arithmetic in largest machine-supported size (intmax_t)
735         posix mode and posix conformance
736         command hashing
737         tilde expansion for assignment statements that look like $PATH
738         process substitution with named pipes if /dev/fd is not available
739         the ${!param} indirect parameter expansion operator
740         the ${!param*} prefix expansion operator
741         the ${param:offset[:length]} parameter substring operator
742         the ${param/pat[/string]} parameter pattern substitution operator
743         variables: BASH, BASH_VERSION, BASH_VERSINFO, UID, EUID, SHLVL,
744                    TIMEFORMAT, HISTCMD, HOSTTYPE, OSTYPE, MACHTYPE,
745                    HISTFILESIZE, HISTIGNORE, HISTCONTROL, PROMPT_COMMAND,
746                    IGNOREEOF, FIGNORE, INPUTRC, HOSTFILE, DIRSTACK,
747                    PIPESTATUS, HOSTNAME, OPTERR, SHELLOPTS, GLOBIGNORE,
748                    GROUPS, FUNCNAME, histchars, auto_resume
749         prompt expansion with backslash escapes and command substitution
750         redirection: &> (stdout and stderr), <<<, [n]<&word-, [n]>&word-
751         more extensive and extensible editing and programmable completion
752         builtins: bind, builtin, command, declare, dirs, echo -e/-E, enable,
753                   exec -l/-c/-a, fc -s, export -n/-f/-p, hash, help, history,
754                   jobs -x/-r/-s, kill -s/-n/-l, local, logout, popd, pushd,
755                   read -e/-p/-a/-t/-n/-d/-s, readonly -a/-n/-f/-p,
756                   set -o braceexpand/-o histexpand/-o interactive-comments/
757                   -o notify/-o physical/-o posix/-o hashall/-o onecmd/
758                   -h/-B/-C/-b/-H/-P, set +o, suspend, trap -l, type,
759                   typeset -a/-F/-p, ulimit -u, umask -S, alias -p, shopt,
760                   disown, printf, complete, compgen
761         `!' csh-style history expansion
762         POSIX.2-style globbing character classes
763         POSIX.2-style globbing equivalence classes
764         POSIX.2-style globbing collating symbols
765         egrep-like extended pattern matching operators
766         case-insensitive pattern matching and globbing
767         `**' arithmetic operator to do exponentiation
768         redirection to /dev/fd/N, /dev/stdin, /dev/stdout, /dev/stderr
769         arrays of unlimited size
770         TMOUT is default timeout for `read' and `select'
771
772 Things ksh88 has or uses that bash does not:
773         tracked aliases (alias -t)
774         variables: ERRNO, FPATH, EDITOR, VISUAL
775         co-processes (|&, >&p, <&p)
776         weirdly-scoped functions
777         typeset +f to list all function names without definitions
778         text of command history kept in a file, not memory
779         builtins: alias -x, cd old new, fc -e -, newgrp, print,
780                   read -p/-s/var?prompt, set -A/-o gmacs/
781                   -o bgnice/-o markdirs/-o nolog/-o trackall/-o viraw/-s,
782                   typeset -H/-L/-R/-Z/-A/-ft/-fu/-fx/-l/-u/-t, whence
783         using environment to pass attributes of exported variables
784         arithmetic evaluation done on arguments to some builtins
785         reads .profile from $PWD when invoked as login shell
786
787 Implementation differences:
788         ksh runs last command of a pipeline in parent shell context
789         bash has brace expansion by default (ksh88 compile-time option)
790         bash has fixed startup file for all interactive shells; ksh reads $ENV
791         bash has exported functions
792         bash command search finds functions before builtins
793         bash waits for all commands in pipeline to exit before returning status
794         emacs-mode editing has some slightly different key bindings
795
796 C3)  Which new features in ksh-93 are not in bash, and which are?
797
798 New things in ksh-93 not in bash-2.05b:
799         associative arrays
800         floating point arithmetic and variables
801         math library functions
802         ${!name[sub]} name of subscript for associative array
803         `.' is allowed in variable names to create a hierarchical namespace
804         more extensive compound assignment syntax
805         discipline functions
806         `sleep' and `getconf' builtins (bash has loadable versions)
807         typeset -n and `nameref' variables
808         KEYBD trap
809         variables: .sh.edchar, .sh.edmode, .sh.edcol, .sh.edtext, .sh.version,
810                    .sh.name, .sh.subscript, .sh.value, .sh.match, HISTEDIT
811         backreferences in pattern matching (\N)
812         `&' operator in pattern lists for matching
813         print -f (bash uses printf)
814         `fc' has been renamed to `hist'
815         `.' can execute shell functions
816         exit statuses between 0 and 255
817         set -o pipefail
818         `+=' variable assignment operator
819         FPATH and PATH mixing
820         getopts -a
821         -I invocation option
822         DEBUG trap now executed before each simple command, instead of after
823         printf %H, %P, %T, %Z modifiers, output base for %d
824
825 New things in ksh-93 present in bash-2.05b:
826         [n]<&word- and [n]>&word- redirections (combination dup and close)
827         for (( expr1; expr2; expr3 )) ; do list; done - arithmetic for command
828         ?:, ++, --, `expr1 , expr2' arithmetic operators
829         expansions: ${!param}, ${param:offset[:len]}, ${param/pat[/str]},
830                     ${!param*}
831         compound array assignment
832         the `!' reserved word
833         loadable builtins -- but ksh uses `builtin' while bash uses `enable'
834         `command', `builtin', `disown' builtins
835         new $'...' and $"..." quoting
836         FIGNORE (but bash uses GLOBIGNORE), HISTCMD
837         set -o notify/-C
838         changes to kill builtin
839         read -A (bash uses read -a)
840         read -t/-d
841         trap -p
842         exec -c/-a
843         `.' restores the positional parameters when it completes
844         POSIX.2 `test'
845         umask -S
846         unalias -a
847         command and arithmetic substitution performed on PS1, PS4, and ENV
848         command name completion
849         ENV processed only for interactive shells
850
851 Section D:  Why does bash do some things differently than other Unix shells?
852
853 D1) Why does bash run a different version of `command' than
854     `which command' says it will?
855
856 On many systems, `which' is actually a csh script that assumes
857 you're running csh.  In tcsh, `which' and its cousin `where'
858 are builtins.  On other Unix systems, `which' is a perl script
859 that uses the PATH environment variable.
860
861 The csh script version reads the csh startup files from your
862 home directory and uses those to determine which `command' will
863 be invoked.  Since bash doesn't use any of those startup files,
864 there's a good chance that your bash environment differs from
865 your csh environment.  The bash `type' builtin does everything
866 `which' does, and will report correct results for the running
867 shell.  If you're really wedded to the name `which', try adding
868 the following function definition to your .bashrc:
869
870         which()
871         {
872                 builtin type "$@"
873         }
874
875 If you're moving from tcsh and would like to bring `where' along
876 as well, use this function:
877
878         where()
879         {
880                 builtin type -a "$@"
881         }
882
883 D2) Why doesn't bash treat brace expansions exactly like csh?
884
885 The only difference between bash and csh brace expansion is that
886 bash requires a brace expression to contain at least one unquoted
887 comma if it is to be expanded.  Any brace-surrounded word not
888 containing an unquoted comma is left unchanged by the brace
889 expansion code.  This affords the greatest degree of sh
890 compatibility. 
891
892 Bash, ksh, zsh, and pd-ksh all implement brace expansion this way. 
893
894 D3) Why doesn't bash have csh variable modifiers?
895
896 Posix has specified a more powerful, albeit somewhat more cryptic,
897 mechanism cribbed from ksh, and bash implements it.
898
899 ${parameter%word}
900         Remove smallest suffix pattern.  The WORD is expanded to produce
901         a pattern.  It then expands to the value of PARAMETER, with the
902         smallest portion of the suffix matched by the pattern deleted.
903
904         x=file.c
905         echo ${x%.c}.o
906         -->file.o
907
908 ${parameter%%word}
909
910         Remove largest suffix pattern.  The WORD is expanded to produce
911         a pattern.  It then expands to the value of PARAMETER, with the
912         largest portion of the suffix matched by the pattern deleted.
913
914         x=posix/src/std
915         echo ${x%%/*}
916         -->posix
917
918 ${parameter#word}
919         Remove smallest prefix pattern.  The WORD is expanded to produce
920         a pattern.  It then expands to the value of PARAMETER, with the
921         smallest portion of the prefix matched by the pattern deleted.
922
923         x=$HOME/src/cmd
924         echo ${x#$HOME}
925         -->/src/cmd
926
927 ${parameter##word}
928         Remove largest prefix pattern.  The WORD is expanded to produce
929         a pattern.  It then expands to the value of PARAMETER, with the
930         largest portion of the prefix matched by the pattern deleted.
931
932         x=/one/two/three
933         echo ${x##*/}
934         -->three
935
936
937 Given
938         a=/a/b/c/d
939         b=b.xxx
940
941         csh                     bash            result
942         ---                     ----            ------
943         $a:h                    ${a%/*}            /a/b/c
944         $a:t                    ${a##*/}           d
945         $b:r                    ${b%.*}            b
946         $b:e                    ${b##*.}           xxx
947
948
949 D4) How can I make my csh aliases work when I convert to bash?
950
951 Bash uses a different syntax to support aliases than csh does. 
952 The details can be found in the documentation.  We have provided
953 a shell script which does most of the work of conversion for you;
954 this script can be found in ./examples/misc/aliasconv.sh.  Here is
955 how you use it:
956   
957 Start csh in the normal way for you.  (e.g., `csh')
958   
959 Pipe the output of `alias' through `aliasconv.sh', saving the
960 results into `bash_aliases':
961   
962         alias | bash aliasconv.sh >bash_aliases
963   
964 Edit `bash_aliases', carefully reading through any created
965 functions.  You will need to change the names of some csh specific
966 variables to the bash equivalents.  The script converts $cwd to
967 $PWD, $term to $TERM, $home to $HOME, $user to $USER, and $prompt
968 to $PS1.  You may also have to add quotes to avoid unwanted
969 expansion.
970
971 For example, the csh alias:
972   
973         alias cd 'cd \!*; echo $cwd'
974   
975 is converted to the bash function:
976
977         cd () { command cd "$@"; echo $PWD ; }
978
979 The only thing that needs to be done is to quote $PWD:
980   
981         cd () { command cd "$@"; echo "$PWD" ; }
982   
983 Merge the edited file into your ~/.bashrc.
984
985 There is an additional, more ambitious, script in
986 examples/misc/cshtobash that attempts to convert your entire csh
987 environment to its bash equivalent.  This script can be run as
988 simply `cshtobash' to convert your normal interactive
989 environment, or as `cshtobash ~/.login' to convert your login
990 environment. 
991
992 D5) How can I pipe standard output and standard error from one command to
993     another, like csh does with `|&'?
994
995 Use
996         command 2>&1 | command2
997
998 The key is to remember that piping is performed before redirection, so
999 file descriptor 1 points to the pipe when it is duplicated onto file
1000 descriptor 2.
1001
1002 D6) Now that I've converted from ksh to bash, are there equivalents to
1003     ksh features like autoloaded functions and the `whence' command?
1004
1005 There are features in ksh-88 and ksh-93 that do not have direct bash
1006 equivalents.  Most, however, can be emulated with very little trouble.
1007
1008 ksh-88 feature          Bash equivalent
1009 --------------          ---------------
1010 compiled-in aliases     set up aliases in .bashrc; some ksh aliases are
1011                         bash builtins (hash, history, type)
1012 coprocesses             named pipe pairs (one for read, one for write)
1013 typeset +f              declare -F
1014 cd, print, whence       function substitutes in examples/functions/kshenv
1015 autoloaded functions    examples/functions/autoload is the same as typeset -fu
1016 read var?prompt         read -p prompt var
1017
1018 ksh-93 feature          Bash equivalent
1019 --------------          ---------------
1020 sleep, getconf          Bash has loadable versions in examples/loadables
1021 ${.sh.version}          $BASH_VERSION
1022 print -f                printf
1023 hist                    alias hist=fc
1024 $HISTEDIT               $FCEDIT
1025
1026 Section E:  How can I get bash to do certain things, and why does bash do
1027             things the way it does?
1028
1029 E1) Why is the bash builtin `test' slightly different from /bin/test?
1030
1031 The specific example used here is [ ! x -o x ], which is false.
1032
1033 Bash's builtin `test' implements the Posix.2 spec, which can be
1034 summarized as follows (the wording is due to David Korn):
1035    
1036 Here is the set of rules for processing test arguments.
1037   
1038     0 Args: False
1039     1 Arg:  True iff argument is not null.
1040     2 Args: If first arg is !, True iff second argument is null.
1041             If first argument is unary, then true if unary test is true
1042             Otherwise error.
1043     3 Args: If second argument is a binary operator, do binary test of $1 $3
1044             If first argument is !, negate two argument test of $2 $3
1045             If first argument is `(' and third argument is `)', do the
1046             one-argument test of the second argument.
1047             Otherwise error.
1048     4 Args: If first argument is !, negate three argument test of $2 $3 $4.
1049             Otherwise unspecified
1050     5 or more Args: unspecified.  (Historical shells would use their
1051     current algorithm).
1052    
1053 The operators -a and -o are considered binary operators for the purpose
1054 of the 3 Arg case.
1055    
1056 As you can see, the test becomes (not (x or x)), which is false.
1057
1058 E2) Why does bash sometimes say `Broken pipe'?
1059
1060 If a sequence of commands appears in a pipeline, and one of the
1061 reading commands finishes before the writer has finished, the
1062 writer receives a SIGPIPE signal.  Many other shells special-case
1063 SIGPIPE as an exit status in the pipeline and do not report it. 
1064 For example, in:
1065   
1066       ps -aux | head
1067   
1068 `head' can finish before `ps' writes all of its output, and ps
1069 will try to write on a pipe without a reader.  In that case, bash
1070 will print `Broken pipe' to stderr when ps is killed by a
1071 SIGPIPE. 
1072
1073 You can build a version of bash that will not report SIGPIPE errors
1074 by uncommenting the definition of DONT_REPORT_SIGPIPE in the file
1075 config-top.h.
1076
1077 E3) When I have terminal escape sequences in my prompt, why does bash
1078     wrap lines at the wrong column?
1079
1080 Readline, the line editing library that bash uses, does not know
1081 that the terminal escape sequences do not take up space on the
1082 screen.  The redisplay code assumes, unless told otherwise, that
1083 each character in the prompt is a `printable' character that
1084 takes up one character position on the screen. 
1085
1086 You can use the bash prompt expansion facility (see the PROMPTING
1087 section in the manual page) to tell readline that sequences of
1088 characters in the prompt strings take up no screen space. 
1089
1090 Use the \[ escape to begin a sequence of non-printing characters,
1091 and the \] escape to signal the end of such a sequence. 
1092
1093 E4) If I pipe the output of a command into `read variable', why doesn't
1094     the output show up in $variable when the read command finishes?
1095
1096 This has to do with the parent-child relationship between Unix
1097 processes.  It affects all commands run in pipelines, not just
1098 simple calls to `read'.  For example, piping a command's output
1099 into a `while' loop that repeatedly calls `read' will result in
1100 the same behavior.
1101
1102 Each element of a pipeline runs in a separate process, a child of
1103 the shell running the pipeline.  A subprocess cannot affect its
1104 parent's environment.  When the `read' command sets the variable
1105 to the input, that variable is set only in the subshell, not the
1106 parent shell.  When the subshell exits, the value of the variable
1107 is lost. 
1108
1109 Many pipelines that end with `read variable' can be converted
1110 into command substitutions, which will capture the output of
1111 a specified command.  The output can then be assigned to a
1112 variable:
1113
1114         grep ^gnu /usr/lib/news/active | wc -l | read ngroup
1115
1116 can be converted into
1117
1118         ngroup=$(grep ^gnu /usr/lib/news/active | wc -l)
1119
1120 This does not, unfortunately, work to split the text among
1121 multiple variables, as read does when given multiple variable
1122 arguments.  If you need to do this, you can either use the
1123 command substitution above to read the output into a variable
1124 and chop up the variable using the bash pattern removal
1125 expansion operators or use some variant of the following
1126 approach.
1127
1128 Say /usr/local/bin/ipaddr is the following shell script:
1129
1130 #! /bin/sh
1131 host `hostname` | awk '/address/ {print $NF}'
1132
1133 Instead of using
1134
1135         /usr/local/bin/ipaddr | read A B C D
1136
1137 to break the local machine's IP address into separate octets, use
1138
1139         OIFS="$IFS"
1140         IFS=.
1141         set -- $(/usr/local/bin/ipaddr)
1142         IFS="$OIFS"
1143         A="$1" B="$2" C="$3" D="$4"
1144
1145 Beware, however, that this will change the shell's positional
1146 parameters.  If you need them, you should save them before doing
1147 this.
1148
1149 This is the general approach -- in most cases you will not need to
1150 set $IFS to a different value.
1151
1152 Some other user-supplied alternatives include:
1153
1154 read A B C D << HERE
1155     $(IFS=.; echo $(/usr/local/bin/ipaddr))
1156 HERE
1157
1158 and, where process substitution is available,
1159
1160 read A B C D < <(IFS=.; echo $(/usr/local/bin/ipaddr))
1161
1162 E5) I have a bunch of shell scripts that use backslash-escaped characters
1163     in arguments to `echo'.  Bash doesn't interpret these characters.  Why
1164     not, and how can I make it understand them?
1165
1166 This is the behavior of echo on most Unix System V machines.
1167
1168 The bash builtin `echo' is modeled after the 9th Edition
1169 Research Unix version of `echo'.  It does not interpret
1170 backslash-escaped characters in its argument strings by default;
1171 it requires the use of the -e option to enable the
1172 interpretation.  The System V echo provides no way to disable the
1173 special characters; the bash echo has a -E option to disable
1174 them. 
1175
1176 There is a configuration option that will make bash behave like
1177 the System V echo and interpret things like `\t' by default.  Run
1178 configure with the --enable-xpg-echo-default option to turn this
1179 on.  Be aware that this will cause some of the tests run when you
1180 type `make tests' to fail.
1181
1182 There is a shell option, `xpg_echo', settable with `shopt', that will
1183 change the behavior of echo at runtime.  Enabling this option turns
1184 on expansion of backslash-escape sequences.
1185
1186 E6) Why doesn't a while or for loop get suspended when I type ^Z?
1187
1188 This is a consequence of how job control works on Unix.  The only
1189 thing that can be suspended is the process group.  This is a single
1190 command or pipeline of commands that the shell forks and executes.
1191
1192 When you run a while or for loop, the only thing that the shell forks
1193 and executes are any commands in the while loop test and commands in
1194 the loop bodies.  These, therefore, are the only things that can be
1195 suspended when you type ^Z.
1196
1197 If you want to be able to stop the entire loop, you need to put it
1198 within parentheses, which will force the loop into a subshell that
1199 may be stopped (and subsequently restarted) as a single unit.
1200
1201 E7) What about empty for loops in Makefiles?
1202
1203 It's fairly common to see constructs like this in automatically-generated
1204 Makefiles:
1205
1206 SUBDIRS = @SUBDIRS@
1207
1208         ...
1209
1210 subdirs-clean:
1211         for d in ${SUBDIRS}; do \
1212                 ( cd $$d && ${MAKE} ${MFLAGS} clean ) \
1213         done
1214
1215 When SUBDIRS is empty, this results in a command like this being passed to
1216 bash:
1217
1218         for d in ; do
1219                 ( cd $d && ${MAKE} ${MFLAGS} clean )
1220         done
1221
1222 In versions of bash before bash-2.05a, this was a syntax error.  If the
1223 reserved word `in' was present, a word must follow it before the semicolon
1224 or newline.  The language in the manual page referring to the list of words
1225 being empty referred to the list after it is expanded.  These versions of
1226 bash required that there be at least one word following the `in' when the
1227 construct was parsed.
1228
1229 The idiomatic Makefile solution is something like:
1230
1231 SUBDIRS = @SUBDIRS@
1232
1233 subdirs-clean:
1234         subdirs=$SUBDIRS ; for d in $$subdirs; do \
1235                 ( cd $$d && ${MAKE} ${MFLAGS} clean ) \
1236         done
1237
1238 The latest drafts of the updated POSIX standard have changed this:  the
1239 word list is no longer required.  Bash versions 2.05a and later accept
1240 the new syntax.
1241
1242 E8) Why does the arithmetic evaluation code complain about `08'?
1243
1244 The bash arithmetic evaluation code (used for `let', $(()), (()), and in
1245 other places), interprets a leading `0' in numeric constants as denoting
1246 an octal number, and a leading `0x' as denoting hexadecimal.  This is
1247 in accordance with the POSIX.2 spec, section 2.9.2.1, which states that
1248 arithmetic constants should be handled as signed long integers as defined
1249 by the ANSI/ISO C standard.
1250
1251 The POSIX.2 interpretation committee has confirmed this:
1252
1253 http://www.pasc.org/interps/unofficial/db/p1003.2/pasc-1003.2-173.html
1254
1255 E9) Why does the pattern matching expression [A-Z]* match files beginning
1256     with every letter except `z'?
1257
1258 Bash-2.03, Bash-2.05 and later versions honor the current locale setting
1259 when processing ranges within pattern matching bracket expressions ([A-Z]). 
1260 This is what POSIX.2 and SUSv3/XPG6 specify. 
1261
1262 The behavior of the matcher in bash-2.05 and later versions depends on the
1263 current LC_COLLATE setting.  Setting this variable to `C' or `POSIX' will
1264 result in the traditional behavior ([A-Z] matches all uppercase ASCII
1265 characters).  Many other locales, including the en_US locale (the default
1266 on many US versions of Linux) collate the upper and lower case letters like
1267 this:
1268
1269         AaBb...Zz
1270
1271 which means that [A-Z] matches every letter except `z'.  Others collate like
1272
1273         aAbBcC...zZ
1274
1275 which means that [A-Z] matches every letter except `a'.
1276
1277 The portable way to specify upper case letters is [:upper:] instead of
1278 A-Z; lower case may be specified as [:lower:] instead of a-z.
1279
1280 Look at the manual pages for setlocale(3), strcoll(3), and, if it is
1281 present, locale(1).  If you have locale(1), you can use it to find
1282 your current locale information even if you do not have any of the
1283 LC_ variables set.
1284
1285 My advice is to put
1286
1287         export LC_COLLATE=C
1288
1289 into /etc/profile and inspect any shell scripts run from cron for
1290 constructs like [A-Z].  This will prevent things like
1291
1292         rm [A-Z]*
1293
1294 from removing every file in the current directory except those beginning
1295 with `z' and still allow individual users to change the collation order.
1296 Users may put the above command into their own profiles as well, of course.
1297
1298 E10) Why does `cd //' leave $PWD as `//'?
1299
1300 POSIX.2, in its description of `cd', says that *three* or more leading
1301 slashes may be replaced with a single slash when canonicalizing the
1302 current working directory.
1303
1304 This is, I presume, for historical compatibility.  Certain versions of
1305 Unix, and early network file systems, used paths of the form
1306 //hostname/path to access `path' on server `hostname'.
1307
1308 Section F:  Things to watch out for on certain Unix versions
1309
1310 F1) Why can't I use command line editing in my `cmdtool'?
1311
1312 The problem is `cmdtool' and bash fighting over the input.  When
1313 scrolling is enabled in a cmdtool window, cmdtool puts the tty in
1314 `raw mode' to permit command-line editing using the mouse for
1315 applications that cannot do it themselves.  As a result, bash and
1316 cmdtool each try to read keyboard input immediately, with neither
1317 getting enough of it to be useful.
1318
1319 This mode also causes cmdtool to not implement many of the
1320 terminal functions and control sequences appearing in the
1321 `sun-cmd' termcap entry.  For a more complete explanation, see
1322 that file examples/suncmd.termcap in the bash distribution. 
1323
1324 `xterm' is a better choice, and gets along with bash much more
1325 smoothly.
1326
1327 If you must use cmdtool, you can use the termcap description in
1328 examples/suncmd.termcap.  Set the TERMCAP variable to the terminal
1329 description contained in that file, i.e.
1330
1331 TERMCAP='Mu|sun-cmd:am:bs:km:pt:li#34:co#80:cl=^L:ce=\E[K:cd=\E[J:rs=\E[s:'
1332
1333 Then export TERMCAP and start a new cmdtool window from that shell.
1334 The bash command-line editing should behave better in the new
1335 cmdtool.  If this works, you can put the assignment to TERMCAP
1336 in your bashrc file.
1337
1338 F2) I built bash on Solaris 2.  Why do globbing expansions and filename
1339     completion chop off the first few characters of each filename?
1340
1341 This is the consequence of building bash on SunOS 5 and linking
1342 with the libraries in /usr/ucblib, but using the definitions
1343 and structures from files in /usr/include. 
1344
1345 The actual conflict is between the dirent structure in
1346 /usr/include/dirent.h and the struct returned by the version of
1347 `readdir' in libucb.a (a 4.3-BSD style `struct direct'). 
1348
1349 Make sure you've got /usr/ccs/bin ahead of /usr/ucb in your $PATH
1350 when configuring and building bash.  This will ensure that you
1351 use /usr/ccs/bin/cc or acc instead of /usr/ucb/cc and that you
1352 link with libc before libucb. 
1353
1354 If you have installed the Sun C compiler, you may also need to
1355 put /usr/ccs/bin and /opt/SUNWspro/bin into your $PATH before
1356 /usr/ucb.
1357
1358 F3) Why does bash dump core after I interrupt username completion or
1359     `~user' tilde expansion on a machine running NIS?
1360
1361 This is a famous and long-standing bug in the SunOS YP (sorry, NIS)
1362 client library, which is part of libc.
1363
1364 The YP library code keeps static state -- a pointer into the data
1365 returned from the server.  When YP initializes itself (setpwent),
1366 it looks at this pointer and calls free on it if it's non-null. 
1367 So far, so good. 
1368
1369 If one of the YP functions is interrupted during getpwent (the
1370 exact function is interpretwithsave()), and returns NULL, the
1371 pointer is freed without being reset to NULL, and the function
1372 returns.  The next time getpwent is called, it sees that this
1373 pointer is non-null, calls free, and the bash free() blows up
1374 because it's being asked to free freed memory. 
1375
1376 The traditional Unix mallocs allow memory to be freed multiple
1377 times; that's probably why this has never been fixed.  You can
1378 run configure with the `--without-gnu-malloc' option to use
1379 the C library malloc and avoid the problem.
1380
1381 F4) I'm running SVR4.2.  Why is the line erased every time I type `@'?
1382
1383 The `@' character is the default `line kill' character in most
1384 versions of System V, including SVR4.2.  You can change this
1385 character to whatever you want using `stty'.  For example, to
1386 change the line kill character to control-u, type
1387
1388         stty kill ^U
1389
1390 where the `^' and `U' can be two separate characters.
1391
1392 F5) Why does bash report syntax errors when my C News scripts use a
1393     redirection before a subshell command?
1394
1395 The actual command in question is something like
1396
1397         < file ( command )
1398
1399 According to the grammar given in the POSIX.2 standard, this construct
1400 is, in fact, a syntax error.  Redirections may only precede `simple
1401 commands'.  A subshell construct such as the above is one of the shell's
1402 `compound commands'.  A redirection may only follow a compound command.
1403
1404 This affects the mechanical transformation of commands that use `cat'
1405 to pipe a file into a command (a favorite Useless-Use-Of-Cat topic on
1406 comp.unix.shell).  While most commands of the form
1407
1408         cat file | command
1409
1410 can be converted to `< file command', shell control structures such as
1411 loops and subshells require `command < file'.
1412
1413 The file CWRU/sh-redir-hack in the bash-2.05a distribution is an
1414 (unofficial) patch to parse.y that will modify the grammar to
1415 support this construct.  It will not apply with `patch'; you must
1416 modify parse.y by hand.  Note that if you apply this, you must
1417 recompile with -DREDIRECTION_HACK.  This introduces a large
1418 number of reduce/reduce conflicts into the shell grammar. 
1419
1420 F6) Why can't I use vi-mode editing on Red Hat Linux 6.1?
1421
1422 The short answer is that Red Hat screwed up.
1423
1424 The long answer is that they shipped an /etc/inputrc that only works
1425 for emacs mode editing, and then screwed all the vi users by setting
1426 INPUTRC to /etc/inputrc in /etc/profile.
1427
1428 The short fix is to do one of the following: remove or rename
1429 /etc/inputrc, set INPUTRC=~/.inputrc in ~/.bashrc (or .bash_profile,
1430 but make sure you export it if you do), remove the assignment to
1431 INPUTRC from /etc/profile, add
1432
1433         set keymap emacs
1434
1435 to the beginning of /etc/inputrc, or bracket the key bindings in
1436 /etc/inputrc with these lines
1437
1438         $if mode=emacs
1439                 [...]
1440         $endif
1441
1442 F7) Why do bash-2.05a and bash-2.05b fail to compile `printf.def' on
1443     HP/UX 11.x?
1444
1445 HP/UX's support for long double is imperfect at best.
1446
1447 GCC will support it without problems, but the HP C library functions
1448 like strtold(3) and printf(3) don't actually work with long doubles.
1449 HP implemented a `long_double' type as a 4-element array of 32-bit
1450 ints, and that is what the library functions use.  The ANSI C
1451 `long double' type is a 128-bit floating point scalar.
1452
1453 The easiest fix, until HP fixes things up, is to edit the generated
1454 config.h and #undef the HAVE_LONG_DOUBLE line.  After doing that,
1455 the compilation should complete successfully.
1456
1457 Section G:  How can I get bash to do certain common things?
1458
1459 G1) How can I get bash to read and display eight-bit characters?
1460
1461 This is a process requiring several steps.
1462
1463 First, you must ensure that the `physical' data path is a full eight
1464 bits.  For xterms, for example, the `vt100' resources `eightBitInput'
1465 and `eightBitOutput' should be set to `true'.
1466
1467 Once you have set up an eight-bit path, you must tell the kernel and
1468 tty driver to leave the eighth bit of characters alone when processing
1469 keyboard input.  Use `stty' to do this:
1470
1471         stty cs8 -istrip -parenb
1472
1473 For old BSD-style systems, you can use
1474
1475         stty pass8
1476
1477 You may also need
1478
1479         stty even odd
1480
1481 Finally, you need to tell readline that you will be inputting and
1482 displaying eight-bit characters.  You use readline variables to do
1483 this.  These variables can be set in your .inputrc or using the bash
1484 `bind' builtin.  Here's an example using `bind':
1485
1486         bash$ bind 'set convert-meta off'
1487         bash$ bind 'set meta-flag on'
1488         bash$ bind 'set output-meta on'
1489
1490 The `set' commands between the single quotes may also be placed
1491 in ~/.inputrc.
1492
1493 G2) How do I write a function `x' to replace builtin command `x', but
1494     still invoke the command from within the function?
1495
1496 This is why the `command' and `builtin' builtins exist.  The
1497 `command' builtin executes the command supplied as its first
1498 argument, skipping over any function defined with that name.  The
1499 `builtin' builtin executes the builtin command given as its first
1500 argument directly. 
1501
1502 For example, to write a function to replace `cd' that writes the
1503 hostname and current directory to an xterm title bar, use
1504 something like the following:
1505
1506         cd()
1507         {
1508                 builtin cd "$@" && xtitle "$HOST: $PWD"
1509         }
1510
1511 This could also be written using `command' instead of `builtin';
1512 the version above is marginally more efficient. 
1513
1514 G3) How can I find the value of a shell variable whose name is the value
1515     of another shell variable?
1516
1517 Versions of Bash newer than Bash-2.0 support this directly.  You can use 
1518
1519         ${!var}
1520
1521 For example, the following sequence of commands will echo `z':
1522
1523         var1=var2
1524         var2=z
1525         echo ${!var1}
1526
1527 For sh compatibility, use the `eval' builtin.  The important
1528 thing to remember is that `eval' expands the arguments you give
1529 it again, so you need to quote the parts of the arguments that
1530 you want `eval' to act on. 
1531
1532 For example, this expression prints the value of the last positional
1533 parameter:
1534
1535         eval echo \"\$\{$#\}\"
1536
1537 The expansion of the quoted portions of this expression will be
1538 deferred until `eval' runs, while the `$#' will be expanded
1539 before `eval' is executed.  In versions of bash later than bash-2.0,
1540
1541         echo ${!#}
1542
1543 does the same thing.
1544
1545 This is not the same thing as ksh93 `nameref' variables, though the syntax
1546 is similar.  I may add namerefs in a future bash version.
1547
1548 G4) How can I make the bash `time' reserved word print timing output that
1549      looks like the output from my system's /usr/bin/time?
1550
1551 The bash command timing code looks for a variable `TIMEFORMAT' and
1552 uses its value as a format string to decide how to display the
1553 timing statistics.
1554
1555 The value of TIMEFORMAT is a string with `%' escapes expanded in a
1556 fashion similar in spirit to printf(3).  The manual page explains
1557 the meanings of the escape sequences in the format string.
1558
1559 If TIMEFORMAT is not set, bash acts as if the following assignment had
1560 been performed:
1561
1562         TIMEFORMAT=$'\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS'
1563
1564 The POSIX.2 default time format (used by `time -p command') is
1565
1566         TIMEFORMAT=$'real %2R\nuser %2U\nsys %2S'
1567
1568 The BSD /usr/bin/time format can be emulated with:
1569
1570         TIMEFORMAT=$'\t%1R real\t%1U user\t%1S sys'
1571
1572 The System V /usr/bin/time format can be emulated with:
1573
1574         TIMEFORMAT=$'\nreal\t%1R\nuser\t%1U\nsys\t%1S'
1575
1576 The ksh format can be emulated with:
1577
1578         TIMEFORMAT=$'\nreal\t%2lR\nuser\t%2lU\nsys\t%2lS'
1579
1580 G5) How do I get the current directory into my prompt?
1581
1582 Bash provides a number of backslash-escape sequences which are expanded
1583 when the prompt string (PS1 or PS2) is displayed.  The full list is in
1584 the manual page.
1585
1586 The \w expansion gives the full pathname of the current directory, with
1587 a tilde (`~') substituted for the current value of $HOME.  The \W
1588 expansion gives the basename of the current directory.  To put the full
1589 pathname of the current directory into the path without any tilde
1590 subsitution, use $PWD.  Here are some examples:
1591
1592         PS1='\w$ '      # current directory with tilde
1593         PS1='\W$ '      # basename of current directory
1594         PS1='$PWD$ '    # full pathname of current directory
1595
1596 The single quotes are important in the final example to prevent $PWD from
1597 being expanded when the assignment to PS1 is performed.
1598
1599 G6) How can I rename "*.foo" to "*.bar"?
1600
1601 Use the pattern removal functionality described in D3.  The following `for'
1602 loop will do the trick:
1603
1604         for f in *.foo; do
1605                 mv $f ${f%foo}bar
1606         done
1607
1608 G7) How can I translate a filename from uppercase to lowercase?
1609
1610 The script examples/functions/lowercase, originally written by John DuBois,
1611 will do the trick.  The converse is left as an exercise.
1612
1613 G8) How can I write a filename expansion (globbing) pattern that will match
1614     all files in the current directory except "." and ".."?
1615
1616 You must have set the `extglob' shell option using `shopt -s extglob' to use
1617 this:
1618
1619         echo .!(.|) *
1620
1621 A solution that works without extended globbing is given in the Unix Shell
1622 FAQ, posted periodically to comp.unix.shell.
1623
1624 Section H:  Where do I go from here?
1625
1626 H1) How do I report bugs in bash, and where should I look for fixes and
1627     advice?
1628
1629 Use the `bashbug' script to report bugs.  It is built and
1630 installed at the same time as bash.  It provides a standard
1631 template for reporting a problem and automatically includes
1632 information about your configuration and build environment. 
1633
1634 `bashbug' sends its reports to bug-bash@gnu.org, which
1635 is a large mailing list gatewayed to the usenet newsgroup gnu.bash.bug. 
1636
1637 Bug fixes, answers to questions, and announcements of new releases
1638 are all posted to gnu.bash.bug.  Discussions concerning bash features
1639 and problems also take place there.
1640
1641 To reach the bash maintainers directly, send mail to
1642 bash-maintainers@gnu.org.
1643
1644 H2) What kind of bash documentation is there?
1645
1646 First, look in the doc directory in the bash distribution.  It should
1647 contain at least the following files:
1648
1649 bash.1          an extensive, thorough Unix-style manual page
1650 builtins.1      a manual page covering just bash builtin commands
1651 bashref.texi    a reference manual in GNU tex`info format
1652 bashref.info    an info version of the reference manual
1653 FAQ             this file
1654 article.ms      text of an article written for The Linux Journal
1655 readline.3      a man page describing readline
1656
1657 Postscript, HTML, and ASCII files created from the above source are
1658 available in the documentation distribution.
1659
1660 There is additional documentation available for anonymous FTP from host
1661 ftp.cwru.edu in the `pub/bash' directory.
1662
1663 Cameron Newham and Bill Rosenblatt have written a book on bash, published
1664 by O'Reilly and Associates.  The book is based on Bill Rosenblatt's Korn
1665 Shell book.  The title is ``Learning the Bash Shell'', and the ISBN number
1666 is 1-56592-147-X.  Look for it in fine bookstores near you.  This book
1667 covers bash-1.14, but has an appendix describing some of the new features
1668 in bash-2.0.  
1669
1670 A second edition of this book is available, published in January, 1998.
1671 The ISBN number is 1-56592-347-2.  Look for it in the same fine bookstores
1672 or on the web.
1673
1674 H3) What's coming in future versions?
1675
1676 These are features I hope to include in a future version of bash.
1677
1678 a better bash debugger (a minimally-tested version is included with bash-2.05b)
1679 associative arrays
1680 co-processes, but with a new-style syntax that looks like function declaration
1681
1682 H4) What's on the bash `wish list' for future versions?
1683
1684 These are features that may or may not appear in a future version of bash.
1685
1686 breaking some of the shell functionality into embeddable libraries
1687 a module system like zsh's, using dynamic loading like builtins
1688 better internationalization using GNU `gettext'
1689 date-stamped command history
1690 a bash programmer's guide with a chapter on creating loadable builtins
1691 a better loadable interface to perl with access to the shell builtins and
1692         variables (contributions gratefully accepted)
1693 ksh93-like `nameref' variables
1694 ksh93-like `+=' variable assignment operator
1695 ksh93-like `xx.yy' variables (including some of the .sh.* variables) and
1696         associated disipline functions
1697 Some of the new ksh93 pattern matching operators, like backreferencing
1698
1699 H5) When will the next release appear?
1700
1701 The next version will appear sometime in 2002.  Never make predictions. 
1702
1703
1704 This document is Copyright 1995-2002 by Chester Ramey.
1705
1706 Permission is hereby granted, without written agreement and
1707 without license or royalty fees, to use, copy, and distribute
1708 this document for any purpose, provided that the above copyright
1709 notice appears in all copies of this document and that the
1710 contents of this document remain unaltered.