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