source: trunk/third/bash/doc/FAQ @ 21276

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