1 From: chet.ramey@case.edu (Chet Ramey)
3 Subject: BASH Frequently-Asked Questions (FAQ version 3.36)
4 Reply-To: chet@po.cwru.edu
5 Archive-name: unix-faq/shell/bash
6 Posting-Frequency: monthly
7 Submitted-By: chet@po.cwru.edu (Chet Ramey)
8 Last-Modified: Fri May 11 16:18:55 EDT 2007
11 URL: ftp://ftp.cwru.edu/pub/bash/FAQ
12 Maintainer: chet@po.cwru.edu (Chet Ramey)
14 This is the Bash FAQ, version 3.36, for Bash version 3.2.
16 This document contains a set of frequently-asked questions concerning
17 Bash, the GNU Bourne-Again Shell. Bash is a freely-available command
18 interpreter with advanced features for both interactive use and shell
21 Another good source of basic information about shells is the collection
22 of FAQ articles periodically posted to comp.unix.shell.
24 Questions and comments concerning this document should be sent to
27 This document is available for anonymous FTP with the URL
29 ftp://ftp.cwru.edu/pub/bash/FAQ
31 The Bash home page is http://cnswww.cns.cwru.edu/~chet/bash/bashtop.html
39 A2) What's the latest version?
40 A3) Where can I get it?
41 A4) On what machines will bash run?
42 A5) Will bash run on operating systems other than Unix?
43 A6) How can I build bash with gcc?
44 A7) How can I make bash my login shell?
45 A8) I just changed my login shell to bash, and now I can't FTP into my
47 A9) What's the `POSIX Shell and Utilities standard'?
48 A10) What is the bash `posix mode'?
50 Section B: The latest version
52 B1) What's new in version 3.2?
53 B2) Are there any user-visible incompatibilities between bash-3.2 and
56 Section C: Differences from other Unix shells
58 C1) How does bash differ from sh, the Bourne shell?
59 C2) How does bash differ from the Korn shell, version ksh88?
60 C3) Which new features in ksh-93 are not in bash, and which are?
62 Section D: Why does bash do some things differently than other Unix shells?
64 D1) Why does bash run a different version of `command' than
65 `which command' says it will?
66 D2) Why doesn't bash treat brace expansions exactly like csh?
67 D3) Why doesn't bash have csh variable modifiers?
68 D4) How can I make my csh aliases work when I convert to bash?
69 D5) How can I pipe standard output and standard error from one command to
70 another, like csh does with `|&'?
71 D6) Now that I've converted from ksh to bash, are there equivalents to
72 ksh features like autoloaded functions and the `whence' command?
74 Section E: Why does bash do certain things the way it does?
76 E1) Why is the bash builtin `test' slightly different from /bin/test?
77 E2) Why does bash sometimes say `Broken pipe'?
78 E3) When I have terminal escape sequences in my prompt, why does bash
79 wrap lines at the wrong column?
80 E4) If I pipe the output of a command into `read variable', why doesn't
81 the output show up in $variable when the read command finishes?
82 E5) I have a bunch of shell scripts that use backslash-escaped characters
83 in arguments to `echo'. Bash doesn't interpret these characters. Why
84 not, and how can I make it understand them?
85 E6) Why doesn't a while or for loop get suspended when I type ^Z?
86 E7) What about empty for loops in Makefiles?
87 E8) Why does the arithmetic evaluation code complain about `08'?
88 E9) Why does the pattern matching expression [A-Z]* match files beginning
89 with every letter except `z'?
90 E10) Why does `cd //' leave $PWD as `//'?
91 E11) If I resize my xterm while another program is running, why doesn't bash
93 E12) Why don't negative offsets in substring expansion work like I expect?
94 E13) Why does filename completion misbehave if a colon appears in the filename?
95 E14) Why does quoting the pattern argument to the regular expression matching
96 conditional operator (=~) cause matching to stop working?
98 Section F: Things to watch out for on certain Unix versions
100 F1) Why can't I use command line editing in my `cmdtool'?
101 F2) I built bash on Solaris 2. Why do globbing expansions and filename
102 completion chop off the first few characters of each filename?
103 F3) Why does bash dump core after I interrupt username completion or
104 `~user' tilde expansion on a machine running NIS?
105 F4) I'm running SVR4.2. Why is the line erased every time I type `@'?
106 F5) Why does bash report syntax errors when my C News scripts use a
107 redirection before a subshell command?
108 F6) Why can't I use vi-mode editing on Red Hat Linux 6.1?
109 F7) Why do bash-2.05a and bash-2.05b fail to compile `printf.def' on
112 Section G: How can I get bash to do certain common things?
114 G1) How can I get bash to read and display eight-bit characters?
115 G2) How do I write a function `x' to replace builtin command `x', but
116 still invoke the command from within the function?
117 G3) How can I find the value of a shell variable whose name is the value
118 of another shell variable?
119 G4) How can I make the bash `time' reserved word print timing output that
120 looks like the output from my system's /usr/bin/time?
121 G5) How do I get the current directory into my prompt?
122 G6) How can I rename "*.foo" to "*.bar"?
123 G7) How can I translate a filename from uppercase to lowercase?
124 G8) How can I write a filename expansion (globbing) pattern that will match
125 all files in the current directory except "." and ".."?
127 Section H: Where do I go from here?
129 H1) How do I report bugs in bash, and where should I look for fixes and
131 H2) What kind of bash documentation is there?
132 H3) What's coming in future versions?
133 H4) What's on the bash `wish list'?
134 H5) When will the next release appear?
137 Section A: The Basics
141 Bash is a Unix command interpreter (shell). It is an implementation of
142 the Posix 1003.2 shell standard, and resembles the Korn and System V
145 Bash contains a number of enhancements over those shells, both
146 for interactive use and shell programming. Features geared
147 toward interactive use include command line editing, command
148 history, job control, aliases, and prompt expansion. Programming
149 features include additional variable expansions, shell
150 arithmetic, and a number of variables and options to control
153 Bash was originally written by Brian Fox of the Free Software
154 Foundation. The current developer and maintainer is Chet Ramey
155 of Case Western Reserve University.
157 A2) What's the latest version?
159 The latest version is 3.2, first made available on 12 October, 2006.
161 A3) Where can I get it?
163 Bash is the GNU project's shell, and so is available from the
164 master GNU archive site, ftp.gnu.org, and its mirrors. The
165 latest version is also available for FTP from ftp.cwru.edu.
166 The following URLs tell how to get version 3.2:
168 ftp://ftp.gnu.org/pub/gnu/bash/bash-3.2.tar.gz
169 ftp://ftp.cwru.edu/pub/bash/bash-3.2.tar.gz
171 Formatted versions of the documentation are available with the URLs:
173 ftp://ftp.gnu.org/pub/gnu/bash/bash-doc-3.2.tar.gz
174 ftp://ftp.cwru.edu/pub/bash/bash-doc-3.2.tar.gz
176 Any patches for the current version are available with the URL:
178 ftp://ftp.cwru.edu/pub/bash/bash-3.2-patches/
180 A4) On what machines will bash run?
182 Bash has been ported to nearly every version of Unix. All you
183 should have to do to build it on a machine for which a port
184 exists is to type `configure' and then `make'. The build process
185 will attempt to discover the version of Unix you have and tailor
186 itself accordingly, using a script created by GNU autoconf.
188 More information appears in the file `INSTALL' in the distribution.
190 The Bash web page (http://cnswww.cns.cwru.edu/~chet/bash/bashtop.html)
191 explains how to obtain binary versions of bash for most of the major
192 commercial Unix systems.
194 A5) Will bash run on operating systems other than Unix?
196 Configuration specifics for Unix-like systems such as QNX and
197 LynxOS are included in the distribution. Bash-2.05 and later
198 versions should compile and run on Minix 2.0 (patches were
199 contributed), but I don't believe anyone has built bash-2.x on
200 earlier Minix versions yet.
202 Bash has been ported to versions of Windows implementing the Win32
203 programming interface. This includes Windows 95 and Windows NT.
204 The port was done by Cygnus Solutions (now part of Red Hat) as part
205 of their CYGWIN project. For more information about the project, see
206 http://www.cygwin.com/.
208 Cygnus originally ported bash-1.14.7, and that port was part of their
209 early GNU-Win32 (the original name) releases. Cygnus has also done
210 ports of bash-2.05b and bash-3.0 to the CYGWIN environment, and both
211 are available as part of their current release. Bash-3.2 is currently
212 being tested and should be available soon.
214 Bash-2.05b and later versions should require no local Cygnus changes to
215 build and run under CYGWIN.
217 DJ Delorie has a port of bash-2.x which runs under MS-DOS, as part
218 of the DJGPP project. For more information on the project, see
220 http://www.delorie.com/djgpp/
222 I have been told that the original DJGPP port was done by Daisuke Aoyama.
224 Mark Elbrecht <snowball3@bigfoot.com> has sent me notice that bash-2.04
225 is available for DJGPP V2. The files are available as:
227 ftp://ftp.simtel.net/pub/simtelnet/gnu/djgpp/v2gnu/bsh204b.zip binary
228 ftp://ftp.simtel.net/pub/simtelnet/gnu/djgpp/v2gnu/bsh204d.zip documentation
229 ftp://ftp.simtel.net/pub/simtelnet/gnu/djgpp/v2gnu/bsh204s.zip source
231 Mark began to work with bash-2.05, but I don't know the current status.
233 Bash-3.0 compiles and runs with no modifications under Microsoft's Services
234 for Unix (SFU), once known as Interix. I do not anticipate any problems
235 with building bash-3.1 or bash-3.2.
237 A6) How can I build bash with gcc?
239 Bash configures to use gcc by default if it is available. Read the
240 file INSTALL in the distribution for more information.
242 A7) How can I make bash my login shell?
244 Some machines let you use `chsh' to change your login shell. Other
245 systems use `passwd -s' or `passwd -e'. If one of these works for
246 you, that's all you need. Note that many systems require the full
247 pathname to a shell to appear in /etc/shells before you can make it
248 your login shell. For this, you may need the assistance of your
249 friendly local system administrator.
251 If you cannot do this, you can still use bash as your login shell, but
252 you need to perform some tricks. The basic idea is to add a command
253 to your login shell's startup file to replace your login shell with
256 For example, if your login shell is csh or tcsh, and you have installed
257 bash in /usr/gnu/bin/bash, add the following line to ~/.login:
259 if ( -f /usr/gnu/bin/bash ) exec /usr/gnu/bin/bash --login
261 (the `--login' tells bash that it is a login shell).
263 It's not a good idea to put this command into ~/.cshrc, because every
264 csh you run without the `-f' option, even ones started to run csh scripts,
265 reads that file. If you must put the command in ~/.cshrc, use something
268 if ( $?prompt ) exec /usr/gnu/bin/bash --login
270 to ensure that bash is exec'd only when the csh is interactive.
272 If your login shell is sh or ksh, you have to do two things.
274 First, create an empty file in your home directory named `.bash_profile'.
275 The existence of this file will prevent the exec'd bash from trying to
276 read ~/.profile, and re-execing itself over and over again. ~/.bash_profile
277 is the first file bash tries to read initialization commands from when
278 it is invoked as a login shell.
280 Next, add a line similar to the above to ~/.profile:
282 [ -f /usr/gnu/bin/bash ] && [ -x /usr/gnu/bin/bash ] && \
283 exec /usr/gnu/bin/bash --login
285 This will cause login shells to replace themselves with bash running as
286 a login shell. Once you have this working, you can copy your initialization
287 code from ~/.profile to ~/.bash_profile.
289 I have received word that the recipe supplied above is insufficient for
290 machines running CDE. CDE has a maze of twisty little startup files, all
293 If you cannot change your login shell in the password file to bash, you
294 will have to (apparently) live with CDE using the shell in the password
295 file to run its startup scripts. If you have changed your shell to bash,
296 there is code in the CDE startup files (on Solaris, at least) that attempts
297 to do the right thing. It is, however, often broken, and may require that
298 you use the $BASH_ENV trick described below.
300 `dtterm' claims to use $SHELL as the default program to start, so if you
301 can change $SHELL in the CDE startup files, you should be able to use bash
302 in your terminal windows.
304 Setting DTSOURCEPROFILE in ~/.dtprofile will cause the `Xsession' program
305 to read your login shell's startup files. You may be able to use bash for
306 the rest of the CDE programs by setting SHELL to bash in ~/.dtprofile as
307 well, but I have not tried this.
309 You can use the above `exec' recipe to start bash when not logging in with
310 CDE by testing the value of the DT variable:
312 if [ -n "$DT" ]; then
313 [ -f /usr/gnu/bin/bash ] && exec /usr/gnu/bin/bash --login
316 If CDE starts its shells non-interactively during login, the login shell
317 startup files (~/.profile, ~/.bash_profile) will not be sourced at login.
318 To get around this problem, append a line similar to the following to your
321 BASH_ENV=${HOME}/.bash_profile ; export BASH_ENV
323 and add the following line to the beginning of ~/.bash_profile:
327 A8) I just changed my login shell to bash, and now I can't FTP into my
330 You must add the full pathname to bash to the file /etc/shells. As
331 noted in the answer to the previous question, many systems require
332 this before you can make bash your login shell.
334 Most versions of ftpd use this file to prohibit `special' users
335 such as `uucp' and `news' from using FTP.
337 A9) What's the `POSIX Shell and Utilities standard'?
339 POSIX is a name originally coined by Richard Stallman for a
340 family of open system standards based on UNIX. There are a
341 number of aspects of UNIX under consideration for
342 standardization, from the basic system services at the system
343 call and C library level to applications and tools to system
344 administration and management. Each area of standardization is
345 assigned to a working group in the 1003 series.
347 The POSIX Shell and Utilities standard was originally developed by
348 IEEE Working Group 1003.2 (POSIX.2). Today it has been merged with
349 the original 1003.1 Working Group and is maintained by the Austin
350 Group (a joint working group of the IEEE, The Open Group and
351 ISO/IEC SC22/WG15). Today the Shell and Utilities are a volume
352 within the set of documents that make up IEEE Std 1003.1-2001, and
353 thus now the former POSIX.2 (from 1992) is now part of the current
354 POSIX.1 standard (POSIX 1003.1-2001).
356 The Shell and Utilities volume concentrates on the command
357 interpreter interface and utility programs commonly executed from
358 the command line or by other programs. The standard is freely
359 available on the web at http://www.UNIX-systems.org/version3/ .
360 Work continues at the Austin Group on maintenance issues; see
361 http://www.opengroup.org/austin/ to join the discussions.
363 Bash is concerned with the aspects of the shell's behavior defined
364 by the POSIX Shell and Utilities volume. The shell command
365 language has of course been standardized, including the basic flow
366 control and program execution constructs, I/O redirection and
367 pipelining, argument handling, variable expansion, and quoting.
369 The `special' builtins, which must be implemented as part of the
370 shell to provide the desired functionality, are specified as
371 being part of the shell; examples of these are `eval' and
372 `export'. Other utilities appear in the sections of POSIX not
373 devoted to the shell which are commonly (and in some cases must
374 be) implemented as builtin commands, such as `read' and `test'.
375 POSIX also specifies aspects of the shell's interactive
376 behavior as part of the UPE, including job control and command
377 line editing. Only vi-style line editing commands have been
378 standardized; emacs editing commands were left out due to
381 The latest version of the POSIX Shell and Utilities standard is
382 available (now updated to the 2004 Edition) as part of the Single
383 UNIX Specification Version 3 at
385 http://www.UNIX-systems.org/version3/
387 A10) What is the bash `posix mode'?
389 Although bash is an implementation of the POSIX shell
390 specification, there are areas where the bash default behavior
391 differs from that spec. The bash `posix mode' changes the bash
392 behavior in these areas so that it obeys the spec more closely.
394 Posix mode is entered by starting bash with the --posix or
395 '-o posix' option or executing `set -o posix' after bash is running.
397 The specific aspects of bash which change when posix mode is
398 active are listed in the file POSIX in the bash distribution.
399 They are also listed in a section in the Bash Reference Manual
400 (from which that file is generated).
402 Section B: The latest version
404 B1) What's new in version 3.2?
406 Bash-3.2 is the second maintenance release of the third major release of
407 bash. It contains the following significant new features (see the manual
408 page for complete descriptions and the CHANGES and NEWS files in the
409 bash-3.2 distribution).
411 o Bash-3.2 now checks shell scripts for NUL characters rather than non-printing
412 characters when deciding whether or not a script is a binary file.
414 o Quoting the string argument to the [[ command's =~ (regexp) operator now
415 forces string matching, as with the other pattern-matching operators.
417 A short feature history dating from Bash-2.0:
419 Bash-3.1 contained the following new features:
421 o Bash-3.1 may now be configured and built in a mode that enforces strict
424 o The `+=' assignment operator, which appends to the value of a string or
425 array variable, has been implemented.
427 o It is now possible to ignore case when matching in contexts other than
428 filename generation using the new `nocasematch' shell option.
430 Bash-3.0 contained the following new features:
432 o Features to support the bash debugger have been implemented, and there
433 is a new `extdebug' option to turn the non-default options on
435 o HISTCONTROL is now a colon-separated list of options and has been
436 extended with a new `erasedups' option that will result in only one
437 copy of a command being kept in the history list
439 o Brace expansion has been extended with a new {x..y} form, producing
440 sequences of digits or characters
442 o Timestamps are now kept with history entries, with an option to save
443 and restore them from the history file; there is a new HISTTIMEFORMAT
444 variable describing how to display the timestamps when listing history
447 o The `[[' command can now perform extended regular expression (egrep-like)
448 matching, with matched subexpressions placed in the BASH_REMATCH array
451 o A new `pipefail' option causes a pipeline to return a failure status if
452 any command in it fails
454 o The `jobs', `kill', and `wait' builtins now accept job control notation
455 in their arguments even if job control is not enabled
457 o The `gettext' package and libintl have been integrated, and the shell
458 messages may be translated into other languages
460 Bash-2.05b introduced the following new features:
462 o support for multibyte characters has been added to both bash and readline
464 o the DEBUG trap is now run *before* simple commands, ((...)) commands,
465 [[...]] conditional commands, and for ((...)) loops
467 o the shell now performs arithmetic in the largest integer size the machine
470 o there is a new \D{...} prompt expansion; passes the `...' to strftime(3)
471 and inserts the result into the expanded prompt
473 o there is a new `here-string' redirection operator: <<< word
475 o when displaying variables, function attributes and definitions are shown
476 separately, allowing them to be re-used as input (attempting to re-use
477 the old output would result in syntax errors).
479 o `read' has a new `-u fd' option to read from a specified file descriptor
481 o the bash debugger in examples/bashdb has been modified to work with the
482 new DEBUG trap semantics, the command set has been made more gdb-like,
483 and the changes to $LINENO make debugging functions work better
485 o the expansion of $LINENO inside a shell function is only relative to the
486 function start if the shell is interactive -- if the shell is running a
487 script, $LINENO expands to the line number in the script. This is as
490 Bash-2.05a introduced the following new features:
492 o The `printf' builtin has undergone major work
494 o There is a new read-only `shopt' option: login_shell, which is set by
495 login shells and unset otherwise
497 o New `\A' prompt string escape sequence; expanding to time in 24-hour
500 o New `-A group/-g' option to complete and compgen; goes group name
503 o New [+-]O invocation option to set and unset `shopt' options at startup
505 o ksh-like `ERR' trap
507 o `for' loops now allow empty word lists after the `in' reserved word
509 o new `hard' and `soft' arguments for the `ulimit' builtin
511 o Readline can be configured to place the user at the same point on the line
512 when retrieving commands from the history list
514 o Readline can be configured to skip `hidden' files (filenames with a leading
515 `.' on Unix) when performing completion
517 Bash-2.05 introduced the following new features:
519 o This version has once again reverted to using locales and strcoll(3) when
520 processing pattern matching bracket expressions, as POSIX requires.
521 o Added a new `--init-file' invocation argument as a synonym for `--rcfile',
522 per the new GNU coding standards.
523 o The /dev/tcp and /dev/udp redirections now accept service names as well as
525 o `complete' and `compgen' now take a `-o value' option, which controls some
526 of the aspects of that compspec. Valid values are:
528 default - perform bash default completion if programmable
529 completion produces no matches
530 dirnames - perform directory name completion if programmable
531 completion produces no matches
532 filenames - tell readline that the compspec produces filenames,
533 so it can do things like append slashes to
534 directory names and suppress trailing spaces
535 o A new loadable builtin, realpath, which canonicalizes and expands symlinks
536 in pathname arguments.
537 o When `set' is called without options, it prints function defintions in a
538 way that allows them to be reused as input. This affects `declare' and
539 `declare -p' as well. This only happens when the shell is not in POSIX
540 mode, since POSIX.2 forbids this behavior.
542 Bash-2.04 introduced the following new features:
544 o Programmable word completion with the new `complete' and `compgen' builtins;
545 examples are provided in examples/complete/complete-examples
546 o `history' has a new `-d' option to delete a history entry
547 o `bind' has a new `-x' option to bind key sequences to shell commands
548 o The prompt expansion code has new `\j' and `\l' escape sequences
549 o The `no_empty_cmd_completion' shell option, if enabled, inhibits
550 command completion when TAB is typed on an empty line
551 o `help' has a new `-s' option to print a usage synopsis
552 o New arithmetic operators: var++, var--, ++var, --var, expr1,expr2 (comma)
553 o New ksh93-style arithmetic for command:
554 for ((expr1 ; expr2; expr3 )); do list; done
555 o `read' has new options: `-t', `-n', `-d', `-s'
556 o The redirection code handles several filenames specially: /dev/fd/N,
557 /dev/stdin, /dev/stdout, /dev/stderr
558 o The redirection code now recognizes /dev/tcp/HOST/PORT and
559 /dev/udp/HOST/PORT and tries to open a TCP or UDP socket, respectively,
560 to the specified port on the specified host
561 o The ${!prefix*} expansion has been implemented
562 o A new FUNCNAME variable, which expands to the name of a currently-executing
564 o The GROUPS variable is no longer readonly
565 o A new shopt `xpg_echo' variable, to control the behavior of echo with
566 respect to backslash-escape sequences at runtime
567 o The NON_INTERACTIVE_LOGIN_SHELLS #define has returned
569 The version of Readline released with Bash-2.04, Readline-4.1, had several
570 new features as well:
572 o Parentheses matching is always compiled into readline, and controllable
573 with the new `blink-matching-paren' variable
574 o The history-search-forward and history-search-backward functions now leave
575 point at the end of the line when the search string is empty, like
576 reverse-search-history, and forward-search-history
577 o A new function for applications: rl_on_new_line_with_prompt()
578 o New variables for applications: rl_already_prompted, and rl_gnu_readline_p
581 Bash-2.03 had very few new features, in keeping with the convention
582 that odd-numbered releases provide mainly bug fixes. A number of new
583 features were added to Readline, mostly at the request of the Cygnus
586 A new shopt option, `restricted_shell', so that startup files can test
587 whether or not the shell was started in restricted mode
588 Filename generation is now performed on the words between ( and ) in
589 compound array assignments (this is really a bug fix)
590 OLDPWD is now auto-exported, as POSIX.2 requires
591 ENV and BASH_ENV are read-only variables in a restricted shell
592 Bash may now be linked against an already-installed Readline library,
593 as long as the Readline library is version 4 or newer
594 All shells begun with the `--login' option will source the login shell
595 startup files, even if the shell is not interactive
597 There were lots of changes to the version of the Readline library released
598 along with Bash-2.03. For a complete list of the changes, read the file
599 CHANGES in the Bash-2.03 distribution.
601 Bash-2.02 contained the following new features:
603 a new version of malloc (based on the old GNU malloc code in previous
604 bash versions) that is more page-oriented, more conservative
605 with memory usage, does not `orphan' large blocks when they
606 are freed, is usable on 64-bit machines, and has allocation
607 checking turned on unconditionally
608 POSIX.2-style globbing character classes ([:alpha:], [:alnum:], etc.)
609 POSIX.2-style globbing equivalence classes
610 POSIX.2-style globbing collating symbols
611 the ksh [[...]] extended conditional command
612 the ksh egrep-style extended pattern matching operators
613 a new `printf' builtin
614 the ksh-like $(<filename) command substitution, which is equivalent to
616 new tilde prefixes that expand to directories from the directory stack
617 new `**' arithmetic operator to do exponentiation
618 case-insensitive globbing (filename expansion)
619 menu completion a la tcsh
620 `magic-space' history expansion function like tcsh
621 the readline inputrc `language' has a new file inclusion directive ($include)
623 Bash-2.01 contained only a few new features:
625 new `GROUPS' builtin array variable containing the user's group list
626 new bindable readline commands: history-and-alias-expand-line and
629 Bash-2.0 contained extensive changes and new features from bash-1.14.7.
632 new `time' reserved word to time pipelines, shell builtins, and
634 one-dimensional arrays with a new compound assignment statement,
635 appropriate expansion constructs and modifications to some
636 of the builtins (read, declare, etc.) to use them
637 new quoting syntaxes for ANSI-C string expansion and locale-specific
639 new expansions to do substring extraction, pattern replacement, and
640 indirect variable expansion
641 new builtins: `disown' and `shopt'
642 new variables: HISTIGNORE, SHELLOPTS, PIPESTATUS, DIRSTACK, GLOBIGNORE,
643 MACHTYPE, BASH_VERSINFO
644 special handling of many unused or redundant variables removed
645 (e.g., $notify, $glob_dot_filenames, $no_exit_on_failed_exec)
646 dynamic loading of new builtin commands; many loadable examples provided
647 new prompt expansions: \a, \e, \n, \H, \T, \@, \v, \V
648 history and aliases available in shell scripts
649 new readline variables: enable-keypad, mark-directories, input-meta,
650 visible-stats, disable-completion, comment-begin
651 new readline commands to manipulate the mark and operate on the region
652 new readline emacs mode commands and bindings for ksh-88 compatibility
653 updated and extended builtins
655 expanded (and now documented) restricted shell mode
657 implementation stuff:
658 autoconf-based configuration
659 nearly all of the bugs reported since version 1.14 have been fixed
660 most builtins converted to use builtin `getopt' for consistency
661 most builtins use -p option to display output in a reusable form
663 grammar tighter and smaller (66 reduce-reduce conflicts gone)
664 lots of code now smaller and faster
665 test suite greatly expanded
667 B2) Are there any user-visible incompatibilities between bash-3.2 and
670 There are a few incompatibilities between version 2.05b and version 3.2.
671 They are detailed in the file COMPAT in the bash distribution. That file
672 is not meant to be all-encompassing; send mail to bash-maintainers@gnu.org
673 if if you find something that's not mentioned there.
675 Section C: Differences from other Unix shells
677 C1) How does bash differ from sh, the Bourne shell?
679 This is a non-comprehensive list of features that differentiate bash
680 from the SVR4.2 shell. The bash manual page explains these more
683 Things bash has that sh does not:
684 long invocation options
685 [+-]O invocation option
687 `!' reserved word to invert pipeline return value
688 `time' reserved word to time pipelines and shell builtins
689 the `function' reserved word
690 the `select' compound command and reserved word
691 arithmetic for command: for ((expr1 ; expr2; expr3 )); do list; done
692 new $'...' and $"..." quoting
693 the $(...) form of command substitution
694 the $(<filename) form of command substitution, equivalent to
696 the ${#param} parameter value length operator
697 the ${!param} indirect parameter expansion operator
698 the ${!param*} prefix expansion operator
699 the ${param:offset[:length]} parameter substring operator
700 the ${param/pat[/string]} parameter pattern substitution operator
701 expansions to perform substring removal (${p%[%]w}, ${p#[#]w})
702 expansion of positional parameters beyond $9 with ${num}
703 variables: BASH, BASH_VERSION, BASH_VERSINFO, UID, EUID, REPLY,
704 TIMEFORMAT, PPID, PWD, OLDPWD, SHLVL, RANDOM, SECONDS,
705 LINENO, HISTCMD, HOSTTYPE, OSTYPE, MACHTYPE, HOSTNAME,
706 ENV, PS3, PS4, DIRSTACK, PIPESTATUS, HISTSIZE, HISTFILE,
707 HISTFILESIZE, HISTCONTROL, HISTIGNORE, GLOBIGNORE, GROUPS,
708 PROMPT_COMMAND, FCEDIT, FIGNORE, IGNOREEOF, INPUTRC,
709 SHELLOPTS, OPTERR, HOSTFILE, TMOUT, FUNCNAME, histchars,
713 variable arrays with new compound assignment syntax
714 redirections: <>, &>, >|, <<<, [n]<&word-, [n]>&word-
715 prompt string special char translation and variable expansion
716 auto-export of variables in initial environment
717 command search finds functions before builtins
718 bash return builtin will exit a file sourced with `.'
719 builtins: cd -/-L/-P, exec -l/-c/-a, echo -e/-E, hash -d/-l/-p/-t.
720 export -n/-f/-p/name=value, pwd -L/-P,
721 read -e/-p/-a/-t/-n/-d/-s/-u,
722 readonly -a/-f/name=value, trap -l, set +o,
723 set -b/-m/-o option/-h/-p/-B/-C/-H/-P,
724 unset -f/-v, ulimit -i/-m/-p/-q/-u/-x,
725 type -a/-p/-t/-f/-P, suspend -f, kill -n,
726 test -o optname/s1 == s2/s1 < s2/s1 > s2/-nt/-ot/-ef/-O/-G/-S
727 bash reads ~/.bashrc for interactive shells, $ENV for non-interactive
728 bash restricted shell mode is more extensive
729 bash allows functions and variables with the same name
732 arithmetic expansion with $((...)) and `let' builtin
733 the `[[...]]' extended conditional command
735 aliases and alias/unalias builtins
736 local variables in functions and `local' builtin
737 readline and command-line editing with programmable completion
738 command history and history/fc builtins
739 csh-like history expansion
740 other new bash builtins: bind, command, compgen, complete, builtin,
741 declare/typeset, dirs, enable, fc, help,
742 history, logout, popd, pushd, disown, shopt,
745 filename generation when using output redirection (command >a*)
746 POSIX.2-style globbing character classes
747 POSIX.2-style globbing equivalence classes
748 POSIX.2-style globbing collating symbols
749 egrep-like extended pattern matching operators
750 case-insensitive pattern matching and globbing
751 variable assignments preceding commands affect only that command,
752 even for builtins and functions
753 posix mode and strict posix conformance
754 redirection to /dev/fd/N, /dev/stdin, /dev/stdout, /dev/stderr,
755 /dev/tcp/host/port, /dev/udp/host/port
756 debugger support, including `caller' builtin and new variables
758 the `+=' assignment operator
761 Things sh has that bash does not:
762 uses variable SHACCT to do shell accounting
763 includes `stop' builtin (bash can use alias stop='kill -s STOP')
765 turns on job control if called as `jsh'
766 $TIMEOUT (like bash $TMOUT)
767 `^' is a synonym for `|'
768 new SVR4.2 sh builtins: mldmode, priv
770 Implementation differences:
771 redirection to/from compound commands causes sh to create a subshell
772 bash does not allow unbalanced quotes; sh silently inserts them at EOF
773 bash does not mess with signal 11
774 sh sets (euid, egid) to (uid, gid) if -p not supplied and uid < 100
775 bash splits only the results of expansions on IFS, using POSIX.2
776 field splitting rules; sh splits all words on IFS
777 sh does not allow MAILCHECK to be unset (?)
778 sh does not allow traps on SIGALRM or SIGCHLD
779 bash allows multiple option arguments when invoked (e.g. -x -v);
780 sh allows only a single option argument (`sh -x -v' attempts
781 to open a file named `-v', and, on SunOS 4.1.4, dumps core.
782 On Solaris 2.4 and earlier versions, sh goes into an infinite
784 sh exits a script if any builtin fails; bash exits only if one of
785 the POSIX.2 `special' builtins fails
787 C2) How does bash differ from the Korn shell, version ksh88?
789 Things bash has or uses that ksh88 does not:
790 long invocation options
791 [-+]O invocation option
794 arithmetic for command: for ((expr1 ; expr2; expr3 )); do list; done
795 arithmetic in largest machine-supported size (intmax_t)
796 posix mode and posix conformance
798 tilde expansion for assignment statements that look like $PATH
799 process substitution with named pipes if /dev/fd is not available
800 the ${!param} indirect parameter expansion operator
801 the ${!param*} prefix expansion operator
802 the ${param:offset[:length]} parameter substring operator
803 the ${param/pat[/string]} parameter pattern substitution operator
804 variables: BASH, BASH_VERSION, BASH_VERSINFO, UID, EUID, SHLVL,
805 TIMEFORMAT, HISTCMD, HOSTTYPE, OSTYPE, MACHTYPE,
806 HISTFILESIZE, HISTIGNORE, HISTCONTROL, PROMPT_COMMAND,
807 IGNOREEOF, FIGNORE, INPUTRC, HOSTFILE, DIRSTACK,
808 PIPESTATUS, HOSTNAME, OPTERR, SHELLOPTS, GLOBIGNORE,
809 GROUPS, FUNCNAME, histchars, auto_resume
810 prompt expansion with backslash escapes and command substitution
811 redirection: &> (stdout and stderr), <<<, [n]<&word-, [n]>&word-
812 more extensive and extensible editing and programmable completion
813 builtins: bind, builtin, command, declare, dirs, echo -e/-E, enable,
814 exec -l/-c/-a, fc -s, export -n/-f/-p, hash, help, history,
815 jobs -x/-r/-s, kill -s/-n/-l, local, logout, popd, pushd,
816 read -e/-p/-a/-t/-n/-d/-s, readonly -a/-n/-f/-p,
817 set -o braceexpand/-o histexpand/-o interactive-comments/
818 -o notify/-o physical/-o posix/-o hashall/-o onecmd/
819 -h/-B/-C/-b/-H/-P, set +o, suspend, trap -l, type,
820 typeset -a/-F/-p, ulimit -i/-q/-u/-x, umask -S, alias -p,
821 shopt, disown, printf, complete, compgen
822 `!' csh-style history expansion
823 POSIX.2-style globbing character classes
824 POSIX.2-style globbing equivalence classes
825 POSIX.2-style globbing collating symbols
826 egrep-like extended pattern matching operators
827 case-insensitive pattern matching and globbing
828 `**' arithmetic operator to do exponentiation
829 redirection to /dev/fd/N, /dev/stdin, /dev/stdout, /dev/stderr
830 arrays of unlimited size
831 TMOUT is default timeout for `read' and `select'
832 debugger support, including the `caller' builtin
834 Timestamps in history entries
835 {x..y} brace expansion
836 The `+=' assignment operator
838 Things ksh88 has or uses that bash does not:
839 tracked aliases (alias -t)
840 variables: ERRNO, FPATH, EDITOR, VISUAL
841 co-processes (|&, >&p, <&p)
842 weirdly-scoped functions
843 typeset +f to list all function names without definitions
844 text of command history kept in a file, not memory
845 builtins: alias -x, cd old new, newgrp, print,
846 read -p/-s/var?prompt, set -A/-o gmacs/
847 -o bgnice/-o markdirs/-o trackall/-o viraw/-s,
848 typeset -H/-L/-R/-Z/-A/-ft/-fu/-fx/-l/-u/-t, whence
849 using environment to pass attributes of exported variables
850 arithmetic evaluation done on arguments to some builtins
851 reads .profile from $PWD when invoked as login shell
853 Implementation differences:
854 ksh runs last command of a pipeline in parent shell context
855 bash has brace expansion by default (ksh88 compile-time option)
856 bash has fixed startup file for all interactive shells; ksh reads $ENV
857 bash has exported functions
858 bash command search finds functions before builtins
859 bash waits for all commands in pipeline to exit before returning status
860 emacs-mode editing has some slightly different key bindings
862 C3) Which new features in ksh-93 are not in bash, and which are?
864 New things in ksh-93 not in bash-3.2:
866 floating point arithmetic and variables
867 math library functions
868 ${!name[sub]} name of subscript for associative array
869 `.' is allowed in variable names to create a hierarchical namespace
870 more extensive compound assignment syntax
872 `sleep' and `getconf' builtins (bash has loadable versions)
873 typeset -n and `nameref' variables
875 variables: .sh.edchar, .sh.edmode, .sh.edcol, .sh.edtext, .sh.version,
876 .sh.name, .sh.subscript, .sh.value, .sh.match, HISTEDIT
877 backreferences in pattern matching (\N)
878 `&' operator in pattern lists for matching
879 print -f (bash uses printf)
880 `fc' has been renamed to `hist'
881 `.' can execute shell functions
882 exit statuses between 0 and 255
883 FPATH and PATH mixing
886 printf %H, %P, %T, %Z modifiers, output base for %d
887 lexical scoping for local variables in `ksh' functions
888 no scoping for local variables in `POSIX' functions
890 New things in ksh-93 present in bash-3.2:
891 [n]<&word- and [n]>&word- redirections (combination dup and close)
892 for (( expr1; expr2; expr3 )) ; do list; done - arithmetic for command
893 ?:, ++, --, `expr1 , expr2' arithmetic operators
894 expansions: ${!param}, ${param:offset[:len]}, ${param/pat[/str]},
896 compound array assignment
897 the `!' reserved word
898 loadable builtins -- but ksh uses `builtin' while bash uses `enable'
899 `command', `builtin', `disown' builtins
900 new $'...' and $"..." quoting
901 FIGNORE (but bash uses GLOBIGNORE), HISTCMD
903 changes to kill builtin
904 read -A (bash uses read -a)
908 `.' restores the positional parameters when it completes
912 command and arithmetic substitution performed on PS1, PS4, and ENV
913 command name completion
914 ENV processed only for interactive shells
916 The `+=' assignment operator
918 Section D: Why does bash do some things differently than other Unix shells?
920 D1) Why does bash run a different version of `command' than
921 `which command' says it will?
923 On many systems, `which' is actually a csh script that assumes
924 you're running csh. In tcsh, `which' and its cousin `where'
925 are builtins. On other Unix systems, `which' is a perl script
926 that uses the PATH environment variable. Many Linux distributions
927 use GNU `which', which is a C program that can understand shell
930 The csh script version reads the csh startup files from your
931 home directory and uses those to determine which `command' will
932 be invoked. Since bash doesn't use any of those startup files,
933 there's a good chance that your bash environment differs from
934 your csh environment. The bash `type' builtin does everything
935 `which' does, and will report correct results for the running
936 shell. If you're really wedded to the name `which', try adding
937 the following function definition to your .bashrc:
944 If you're moving from tcsh and would like to bring `where' along
945 as well, use this function:
952 D2) Why doesn't bash treat brace expansions exactly like csh?
954 The only difference between bash and csh brace expansion is that
955 bash requires a brace expression to contain at least one unquoted
956 comma if it is to be expanded. Any brace-surrounded word not
957 containing an unquoted comma is left unchanged by the brace
958 expansion code. This affords the greatest degree of sh
961 Bash, ksh, zsh, and pd-ksh all implement brace expansion this way.
963 D3) Why doesn't bash have csh variable modifiers?
965 Posix has specified a more powerful, albeit somewhat more cryptic,
966 mechanism cribbed from ksh, and bash implements it.
969 Remove smallest suffix pattern. The WORD is expanded to produce
970 a pattern. It then expands to the value of PARAMETER, with the
971 smallest portion of the suffix matched by the pattern deleted.
979 Remove largest suffix pattern. The WORD is expanded to produce
980 a pattern. It then expands to the value of PARAMETER, with the
981 largest portion of the suffix matched by the pattern deleted.
988 Remove smallest prefix pattern. The WORD is expanded to produce
989 a pattern. It then expands to the value of PARAMETER, with the
990 smallest portion of the prefix matched by the pattern deleted.
997 Remove largest prefix pattern. The WORD is expanded to produce
998 a pattern. It then expands to the value of PARAMETER, with the
999 largest portion of the prefix matched by the pattern deleted.
1018 D4) How can I make my csh aliases work when I convert to bash?
1020 Bash uses a different syntax to support aliases than csh does.
1021 The details can be found in the documentation. We have provided
1022 a shell script which does most of the work of conversion for you;
1023 this script can be found in ./examples/misc/aliasconv.sh. Here is
1026 Start csh in the normal way for you. (e.g., `csh')
1028 Pipe the output of `alias' through `aliasconv.sh', saving the
1029 results into `bash_aliases':
1031 alias | bash aliasconv.sh >bash_aliases
1033 Edit `bash_aliases', carefully reading through any created
1034 functions. You will need to change the names of some csh specific
1035 variables to the bash equivalents. The script converts $cwd to
1036 $PWD, $term to $TERM, $home to $HOME, $user to $USER, and $prompt
1037 to $PS1. You may also have to add quotes to avoid unwanted
1040 For example, the csh alias:
1042 alias cd 'cd \!*; echo $cwd'
1044 is converted to the bash function:
1046 cd () { command cd "$@"; echo $PWD ; }
1048 The only thing that needs to be done is to quote $PWD:
1050 cd () { command cd "$@"; echo "$PWD" ; }
1052 Merge the edited file into your ~/.bashrc.
1054 There is an additional, more ambitious, script in
1055 examples/misc/cshtobash that attempts to convert your entire csh
1056 environment to its bash equivalent. This script can be run as
1057 simply `cshtobash' to convert your normal interactive
1058 environment, or as `cshtobash ~/.login' to convert your login
1061 D5) How can I pipe standard output and standard error from one command to
1062 another, like csh does with `|&'?
1065 command 2>&1 | command2
1067 The key is to remember that piping is performed before redirection, so
1068 file descriptor 1 points to the pipe when it is duplicated onto file
1071 D6) Now that I've converted from ksh to bash, are there equivalents to
1072 ksh features like autoloaded functions and the `whence' command?
1074 There are features in ksh-88 and ksh-93 that do not have direct bash
1075 equivalents. Most, however, can be emulated with very little trouble.
1077 ksh-88 feature Bash equivalent
1078 -------------- ---------------
1079 compiled-in aliases set up aliases in .bashrc; some ksh aliases are
1080 bash builtins (hash, history, type)
1081 coprocesses named pipe pairs (one for read, one for write)
1082 typeset +f declare -F
1083 cd, print, whence function substitutes in examples/functions/kshenv
1084 autoloaded functions examples/functions/autoload is the same as typeset -fu
1085 read var?prompt read -p prompt var
1087 ksh-93 feature Bash equivalent
1088 -------------- ---------------
1089 sleep, getconf Bash has loadable versions in examples/loadables
1090 ${.sh.version} $BASH_VERSION
1095 Section E: How can I get bash to do certain things, and why does bash do
1096 things the way it does?
1098 E1) Why is the bash builtin `test' slightly different from /bin/test?
1100 The specific example used here is [ ! x -o x ], which is false.
1102 Bash's builtin `test' implements the Posix.2 spec, which can be
1103 summarized as follows (the wording is due to David Korn):
1105 Here is the set of rules for processing test arguments.
1108 1 Arg: True iff argument is not null.
1109 2 Args: If first arg is !, True iff second argument is null.
1110 If first argument is unary, then true if unary test is true
1112 3 Args: If second argument is a binary operator, do binary test of $1 $3
1113 If first argument is !, negate two argument test of $2 $3
1114 If first argument is `(' and third argument is `)', do the
1115 one-argument test of the second argument.
1117 4 Args: If first argument is !, negate three argument test of $2 $3 $4.
1118 Otherwise unspecified
1119 5 or more Args: unspecified. (Historical shells would use their
1122 The operators -a and -o are considered binary operators for the purpose
1125 As you can see, the test becomes (not (x or x)), which is false.
1127 E2) Why does bash sometimes say `Broken pipe'?
1129 If a sequence of commands appears in a pipeline, and one of the
1130 reading commands finishes before the writer has finished, the
1131 writer receives a SIGPIPE signal. Many other shells special-case
1132 SIGPIPE as an exit status in the pipeline and do not report it.
1137 `head' can finish before `ps' writes all of its output, and ps
1138 will try to write on a pipe without a reader. In that case, bash
1139 will print `Broken pipe' to stderr when ps is killed by a
1142 As of bash-3.1, bash does not report SIGPIPE errors by default. You
1143 can build a version of bash that will report such errors.
1145 E3) When I have terminal escape sequences in my prompt, why does bash
1146 wrap lines at the wrong column?
1148 Readline, the line editing library that bash uses, does not know
1149 that the terminal escape sequences do not take up space on the
1150 screen. The redisplay code assumes, unless told otherwise, that
1151 each character in the prompt is a `printable' character that
1152 takes up one character position on the screen.
1154 You can use the bash prompt expansion facility (see the PROMPTING
1155 section in the manual page) to tell readline that sequences of
1156 characters in the prompt strings take up no screen space.
1158 Use the \[ escape to begin a sequence of non-printing characters,
1159 and the \] escape to signal the end of such a sequence.
1161 E4) If I pipe the output of a command into `read variable', why doesn't
1162 the output show up in $variable when the read command finishes?
1164 This has to do with the parent-child relationship between Unix
1165 processes. It affects all commands run in pipelines, not just
1166 simple calls to `read'. For example, piping a command's output
1167 into a `while' loop that repeatedly calls `read' will result in
1170 Each element of a pipeline, even a builtin or shell function,
1171 runs in a separate process, a child of the shell running the
1172 pipeline. A subprocess cannot affect its parent's environment.
1173 When the `read' command sets the variable to the input, that
1174 variable is set only in the subshell, not the parent shell. When
1175 the subshell exits, the value of the variable is lost.
1177 Many pipelines that end with `read variable' can be converted
1178 into command substitutions, which will capture the output of
1179 a specified command. The output can then be assigned to a
1182 grep ^gnu /usr/lib/news/active | wc -l | read ngroup
1184 can be converted into
1186 ngroup=$(grep ^gnu /usr/lib/news/active | wc -l)
1188 This does not, unfortunately, work to split the text among
1189 multiple variables, as read does when given multiple variable
1190 arguments. If you need to do this, you can either use the
1191 command substitution above to read the output into a variable
1192 and chop up the variable using the bash pattern removal
1193 expansion operators or use some variant of the following
1196 Say /usr/local/bin/ipaddr is the following shell script:
1199 host `hostname` | awk '/address/ {print $NF}'
1203 /usr/local/bin/ipaddr | read A B C D
1205 to break the local machine's IP address into separate octets, use
1209 set -- $(/usr/local/bin/ipaddr)
1211 A="$1" B="$2" C="$3" D="$4"
1213 Beware, however, that this will change the shell's positional
1214 parameters. If you need them, you should save them before doing
1217 This is the general approach -- in most cases you will not need to
1218 set $IFS to a different value.
1220 Some other user-supplied alternatives include:
1222 read A B C D << HERE
1223 $(IFS=.; echo $(/usr/local/bin/ipaddr))
1226 and, where process substitution is available,
1228 read A B C D < <(IFS=.; echo $(/usr/local/bin/ipaddr))
1230 E5) I have a bunch of shell scripts that use backslash-escaped characters
1231 in arguments to `echo'. Bash doesn't interpret these characters. Why
1232 not, and how can I make it understand them?
1234 This is the behavior of echo on most Unix System V machines.
1236 The bash builtin `echo' is modeled after the 9th Edition
1237 Research Unix version of `echo'. It does not interpret
1238 backslash-escaped characters in its argument strings by default;
1239 it requires the use of the -e option to enable the
1240 interpretation. The System V echo provides no way to disable the
1241 special characters; the bash echo has a -E option to disable
1244 There is a configuration option that will make bash behave like
1245 the System V echo and interpret things like `\t' by default. Run
1246 configure with the --enable-xpg-echo-default option to turn this
1247 on. Be aware that this will cause some of the tests run when you
1248 type `make tests' to fail.
1250 There is a shell option, `xpg_echo', settable with `shopt', that will
1251 change the behavior of echo at runtime. Enabling this option turns
1252 on expansion of backslash-escape sequences.
1254 E6) Why doesn't a while or for loop get suspended when I type ^Z?
1256 This is a consequence of how job control works on Unix. The only
1257 thing that can be suspended is the process group. This is a single
1258 command or pipeline of commands that the shell forks and executes.
1260 When you run a while or for loop, the only thing that the shell forks
1261 and executes are any commands in the while loop test and commands in
1262 the loop bodies. These, therefore, are the only things that can be
1263 suspended when you type ^Z.
1265 If you want to be able to stop the entire loop, you need to put it
1266 within parentheses, which will force the loop into a subshell that
1267 may be stopped (and subsequently restarted) as a single unit.
1269 E7) What about empty for loops in Makefiles?
1271 It's fairly common to see constructs like this in automatically-generated
1279 for d in ${SUBDIRS}; do \
1280 ( cd $$d && ${MAKE} ${MFLAGS} clean ) \
1283 When SUBDIRS is empty, this results in a command like this being passed to
1287 ( cd $d && ${MAKE} ${MFLAGS} clean )
1290 In versions of bash before bash-2.05a, this was a syntax error. If the
1291 reserved word `in' was present, a word must follow it before the semicolon
1292 or newline. The language in the manual page referring to the list of words
1293 being empty referred to the list after it is expanded. These versions of
1294 bash required that there be at least one word following the `in' when the
1295 construct was parsed.
1297 The idiomatic Makefile solution is something like:
1302 subdirs=$SUBDIRS ; for d in $$subdirs; do \
1303 ( cd $$d && ${MAKE} ${MFLAGS} clean ) \
1306 The latest updated POSIX standard has changed this: the word list
1307 is no longer required. Bash versions 2.05a and later accept the
1310 E8) Why does the arithmetic evaluation code complain about `08'?
1312 The bash arithmetic evaluation code (used for `let', $(()), (()), and in
1313 other places), interprets a leading `0' in numeric constants as denoting
1314 an octal number, and a leading `0x' as denoting hexadecimal. This is
1315 in accordance with the POSIX.2 spec, section 2.9.2.1, which states that
1316 arithmetic constants should be handled as signed long integers as defined
1317 by the ANSI/ISO C standard.
1319 The POSIX.2 interpretation committee has confirmed this:
1321 http://www.pasc.org/interps/unofficial/db/p1003.2/pasc-1003.2-173.html
1323 E9) Why does the pattern matching expression [A-Z]* match files beginning
1324 with every letter except `z'?
1326 Bash-2.03, Bash-2.05 and later versions honor the current locale setting
1327 when processing ranges within pattern matching bracket expressions ([A-Z]).
1328 This is what POSIX.2 and SUSv3/XPG6 specify.
1330 The behavior of the matcher in bash-2.05 and later versions depends on the
1331 current LC_COLLATE setting. Setting this variable to `C' or `POSIX' will
1332 result in the traditional behavior ([A-Z] matches all uppercase ASCII
1333 characters). Many other locales, including the en_US locale (the default
1334 on many US versions of Linux) collate the upper and lower case letters like
1339 which means that [A-Z] matches every letter except `z'. Others collate like
1343 which means that [A-Z] matches every letter except `a'.
1345 The portable way to specify upper case letters is [:upper:] instead of
1346 A-Z; lower case may be specified as [:lower:] instead of a-z.
1348 Look at the manual pages for setlocale(3), strcoll(3), and, if it is
1349 present, locale(1). If you have locale(1), you can use it to find
1350 your current locale information even if you do not have any of the
1357 into /etc/profile and inspect any shell scripts run from cron for
1358 constructs like [A-Z]. This will prevent things like
1362 from removing every file in the current directory except those beginning
1363 with `z' and still allow individual users to change the collation order.
1364 Users may put the above command into their own profiles as well, of course.
1366 E10) Why does `cd //' leave $PWD as `//'?
1368 POSIX.2, in its description of `cd', says that *three* or more leading
1369 slashes may be replaced with a single slash when canonicalizing the
1370 current working directory.
1372 This is, I presume, for historical compatibility. Certain versions of
1373 Unix, and early network file systems, used paths of the form
1374 //hostname/path to access `path' on server `hostname'.
1376 E11) If I resize my xterm while another program is running, why doesn't bash
1379 This is another issue that deals with job control.
1381 The kernel maintains a notion of a current terminal process group. Members
1382 of this process group (processes whose process group ID is equal to the
1383 current terminal process group ID) receive terminal-generated signals like
1384 SIGWINCH. (For more details, see the JOB CONTROL section of the bash
1387 If a terminal is resized, the kernel sends SIGWINCH to each member of
1388 the terminal's current process group (the `foreground' process group).
1390 When bash is running with job control enabled, each pipeline (which may be
1391 a single command) is run in its own process group, different from bash's
1392 process group. This foreground process group receives the SIGWINCH; bash
1393 does not. Bash has no way of knowing that the terminal has been resized.
1395 There is a `checkwinsize' option, settable with the `shopt' builtin, that
1396 will cause bash to check the window size and adjust its idea of the
1397 terminal's dimensions each time a process stops or exits and returns control
1398 of the terminal to bash. Enable it with `shopt -s checkwinsize'.
1400 E12) Why don't negative offsets in substring expansion work like I expect?
1402 When substring expansion of the form ${param:offset[:length} is used,
1403 an `offset' that evaluates to a number less than zero counts back from
1404 the end of the expanded value of $param.
1406 When a negative `offset' begins with a minus sign, however, unexpected things
1407 can happen. Consider
1412 intending to print the last four characters of $a. The problem is that
1413 ${param:-word} already has a well-defined meaning: expand to word if the
1414 expanded value of param is unset or null, and $param otherwise.
1416 To use negative offsets that begin with a minus sign, separate the
1417 minus sign and the colon with a space.
1419 E13) Why does filename completion misbehave if a colon appears in the filename?
1421 Filename completion (and word completion in general) may appear to behave
1422 improperly if there is a colon in the word to be completed.
1424 The colon is special to readline's word completion code: it is one of the
1425 characters that breaks words for the completer. Readline uses these characters
1426 in sort of the same way that bash uses $IFS: they break or separate the words
1427 the completion code hands to the application-specific or default word
1428 completion functions. The original intent was to make it easy to edit
1429 colon-separated lists (such as $PATH in bash) in various applications using
1432 This is complicated by the fact that some versions of the popular
1433 `bash-completion' programmable completion package have problems with the
1434 default completion behavior in the presence of colons.
1436 The current set of completion word break characters is available in bash as
1437 the value of the COMP_WORDBREAKS variable. Removing `:' from that value is
1438 enough to make the colon not special to completion:
1440 COMP_WORDBREAKS=${COMP_WORDBREAKS//:}
1442 You can also quote the colon with a backslash to achieve the same result
1445 E14) Why does quoting the pattern argument to the regular expression matching
1446 conditional operator (=~) cause regexp matching to stop working?
1448 In versions of bash prior to bash-3.2, the effect of quoting the regular
1449 expression argument to the [[ command's =~ operator was not specified.
1450 The practical effect was that double-quoting the pattern argument required
1451 backslashes to quote special pattern characters, which interfered with the
1452 backslash processing performed by double-quoted word expansion and was
1453 inconsistent with how the == shell pattern matching operator treated
1456 In bash-3.2, the shell was changed to internally quote characters in single-
1457 and double-quoted string arguments to the =~ operator, which suppresses the
1458 special meaning of the characters special to regular expression processing
1459 (`.', `[', `\', `(', `), `*', `+', `?', `{', `|', `^', and `$') and forces
1460 them to be matched literally. This is consistent with how the `==' pattern
1461 matching operator treats quoted portions of its pattern argument.
1463 Since the treatment of quoted string arguments was changed, several issues
1464 have arisen, chief among them the problem of white space in pattern arguments
1465 and the differing treatment of quoted strings between bash-3.1 and bash-3.2.
1466 Both problems may be solved by using a shell variable to hold the pattern.
1467 Since word splitting is not performed when expanding shell variables in all
1468 operands of the [[ command, this allows users to quote patterns as they wish
1469 when assigning the variable, then expand the values to a single string that
1470 may contain whitespace. The first problem may be solved by using backslashes
1471 or any other quoting mechanism to escape the white space in the patterns.
1473 Section F: Things to watch out for on certain Unix versions
1475 F1) Why can't I use command line editing in my `cmdtool'?
1477 The problem is `cmdtool' and bash fighting over the input. When
1478 scrolling is enabled in a cmdtool window, cmdtool puts the tty in
1479 `raw mode' to permit command-line editing using the mouse for
1480 applications that cannot do it themselves. As a result, bash and
1481 cmdtool each try to read keyboard input immediately, with neither
1482 getting enough of it to be useful.
1484 This mode also causes cmdtool to not implement many of the
1485 terminal functions and control sequences appearing in the
1486 `sun-cmd' termcap entry. For a more complete explanation, see
1487 that file examples/suncmd.termcap in the bash distribution.
1489 `xterm' is a better choice, and gets along with bash much more
1492 If you must use cmdtool, you can use the termcap description in
1493 examples/suncmd.termcap. Set the TERMCAP variable to the terminal
1494 description contained in that file, i.e.
1496 TERMCAP='Mu|sun-cmd:am:bs:km:pt:li#34:co#80:cl=^L:ce=\E[K:cd=\E[J:rs=\E[s:'
1498 Then export TERMCAP and start a new cmdtool window from that shell.
1499 The bash command-line editing should behave better in the new
1500 cmdtool. If this works, you can put the assignment to TERMCAP
1501 in your bashrc file.
1503 F2) I built bash on Solaris 2. Why do globbing expansions and filename
1504 completion chop off the first few characters of each filename?
1506 This is the consequence of building bash on SunOS 5 and linking
1507 with the libraries in /usr/ucblib, but using the definitions
1508 and structures from files in /usr/include.
1510 The actual conflict is between the dirent structure in
1511 /usr/include/dirent.h and the struct returned by the version of
1512 `readdir' in libucb.a (a 4.3-BSD style `struct direct').
1514 Make sure you've got /usr/ccs/bin ahead of /usr/ucb in your $PATH
1515 when configuring and building bash. This will ensure that you
1516 use /usr/ccs/bin/cc or acc instead of /usr/ucb/cc and that you
1517 link with libc before libucb.
1519 If you have installed the Sun C compiler, you may also need to
1520 put /usr/ccs/bin and /opt/SUNWspro/bin into your $PATH before
1523 F3) Why does bash dump core after I interrupt username completion or
1524 `~user' tilde expansion on a machine running NIS?
1526 This is a famous and long-standing bug in the SunOS YP (sorry, NIS)
1527 client library, which is part of libc.
1529 The YP library code keeps static state -- a pointer into the data
1530 returned from the server. When YP initializes itself (setpwent),
1531 it looks at this pointer and calls free on it if it's non-null.
1534 If one of the YP functions is interrupted during getpwent (the
1535 exact function is interpretwithsave()), and returns NULL, the
1536 pointer is freed without being reset to NULL, and the function
1537 returns. The next time getpwent is called, it sees that this
1538 pointer is non-null, calls free, and the bash free() blows up
1539 because it's being asked to free freed memory.
1541 The traditional Unix mallocs allow memory to be freed multiple
1542 times; that's probably why this has never been fixed. You can
1543 run configure with the `--without-gnu-malloc' option to use
1544 the C library malloc and avoid the problem.
1546 F4) I'm running SVR4.2. Why is the line erased every time I type `@'?
1548 The `@' character is the default `line kill' character in most
1549 versions of System V, including SVR4.2. You can change this
1550 character to whatever you want using `stty'. For example, to
1551 change the line kill character to control-u, type
1555 where the `^' and `U' can be two separate characters.
1557 F5) Why does bash report syntax errors when my C News scripts use a
1558 redirection before a subshell command?
1560 The actual command in question is something like
1564 According to the grammar given in the POSIX.2 standard, this construct
1565 is, in fact, a syntax error. Redirections may only precede `simple
1566 commands'. A subshell construct such as the above is one of the shell's
1567 `compound commands'. A redirection may only follow a compound command.
1569 This affects the mechanical transformation of commands that use `cat'
1570 to pipe a file into a command (a favorite Useless-Use-Of-Cat topic on
1571 comp.unix.shell). While most commands of the form
1575 can be converted to `< file command', shell control structures such as
1576 loops and subshells require `command < file'.
1578 The file CWRU/sh-redir-hack in the bash distribution is an
1579 (unofficial) patch to parse.y that will modify the grammar to
1580 support this construct. It will not apply with `patch'; you must
1581 modify parse.y by hand. Note that if you apply this, you must
1582 recompile with -DREDIRECTION_HACK. This introduces a large
1583 number of reduce/reduce conflicts into the shell grammar.
1585 F6) Why can't I use vi-mode editing on Red Hat Linux 6.1?
1587 The short answer is that Red Hat screwed up.
1589 The long answer is that they shipped an /etc/inputrc that only works
1590 for emacs mode editing, and then screwed all the vi users by setting
1591 INPUTRC to /etc/inputrc in /etc/profile.
1593 The short fix is to do one of the following: remove or rename
1594 /etc/inputrc, set INPUTRC=~/.inputrc in ~/.bashrc (or .bash_profile,
1595 but make sure you export it if you do), remove the assignment to
1596 INPUTRC from /etc/profile, add
1600 to the beginning of /etc/inputrc, or bracket the key bindings in
1601 /etc/inputrc with these lines
1607 F7) Why do bash-2.05a and bash-2.05b fail to compile `printf.def' on
1610 HP/UX's support for long double is imperfect at best.
1612 GCC will support it without problems, but the HP C library functions
1613 like strtold(3) and printf(3) don't actually work with long doubles.
1614 HP implemented a `long_double' type as a 4-element array of 32-bit
1615 ints, and that is what the library functions use. The ANSI C
1616 `long double' type is a 128-bit floating point scalar.
1618 The easiest fix, until HP fixes things up, is to edit the generated
1619 config.h and #undef the HAVE_LONG_DOUBLE line. After doing that,
1620 the compilation should complete successfully.
1622 Section G: How can I get bash to do certain common things?
1624 G1) How can I get bash to read and display eight-bit characters?
1626 This is a process requiring several steps.
1628 First, you must ensure that the `physical' data path is a full eight
1629 bits. For xterms, for example, the `vt100' resources `eightBitInput'
1630 and `eightBitOutput' should be set to `true'.
1632 Once you have set up an eight-bit path, you must tell the kernel and
1633 tty driver to leave the eighth bit of characters alone when processing
1634 keyboard input. Use `stty' to do this:
1636 stty cs8 -istrip -parenb
1638 For old BSD-style systems, you can use
1646 Finally, you need to tell readline that you will be inputting and
1647 displaying eight-bit characters. You use readline variables to do
1648 this. These variables can be set in your .inputrc or using the bash
1649 `bind' builtin. Here's an example using `bind':
1651 bash$ bind 'set convert-meta off'
1652 bash$ bind 'set meta-flag on'
1653 bash$ bind 'set output-meta on'
1655 The `set' commands between the single quotes may also be placed
1658 The script examples/scripts.noah/meta.bash encapsulates the bind
1659 commands in a shell function.
1661 G2) How do I write a function `x' to replace builtin command `x', but
1662 still invoke the command from within the function?
1664 This is why the `command' and `builtin' builtins exist. The
1665 `command' builtin executes the command supplied as its first
1666 argument, skipping over any function defined with that name. The
1667 `builtin' builtin executes the builtin command given as its first
1670 For example, to write a function to replace `cd' that writes the
1671 hostname and current directory to an xterm title bar, use
1672 something like the following:
1676 builtin cd "$@" && xtitle "$HOST: $PWD"
1679 This could also be written using `command' instead of `builtin';
1680 the version above is marginally more efficient.
1682 G3) How can I find the value of a shell variable whose name is the value
1683 of another shell variable?
1685 Versions of Bash newer than Bash-2.0 support this directly. You can use
1689 For example, the following sequence of commands will echo `z':
1695 For sh compatibility, use the `eval' builtin. The important
1696 thing to remember is that `eval' expands the arguments you give
1697 it again, so you need to quote the parts of the arguments that
1698 you want `eval' to act on.
1700 For example, this expression prints the value of the last positional
1703 eval echo \"\$\{$#\}\"
1705 The expansion of the quoted portions of this expression will be
1706 deferred until `eval' runs, while the `$#' will be expanded
1707 before `eval' is executed. In versions of bash later than bash-2.0,
1711 does the same thing.
1713 This is not the same thing as ksh93 `nameref' variables, though the syntax
1714 is similar. I may add namerefs in a future bash version.
1716 G4) How can I make the bash `time' reserved word print timing output that
1717 looks like the output from my system's /usr/bin/time?
1719 The bash command timing code looks for a variable `TIMEFORMAT' and
1720 uses its value as a format string to decide how to display the
1723 The value of TIMEFORMAT is a string with `%' escapes expanded in a
1724 fashion similar in spirit to printf(3). The manual page explains
1725 the meanings of the escape sequences in the format string.
1727 If TIMEFORMAT is not set, bash acts as if the following assignment had
1730 TIMEFORMAT=$'\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS'
1732 The POSIX.2 default time format (used by `time -p command') is
1734 TIMEFORMAT=$'real %2R\nuser %2U\nsys %2S'
1736 The BSD /usr/bin/time format can be emulated with:
1738 TIMEFORMAT=$'\t%1R real\t%1U user\t%1S sys'
1740 The System V /usr/bin/time format can be emulated with:
1742 TIMEFORMAT=$'\nreal\t%1R\nuser\t%1U\nsys\t%1S'
1744 The ksh format can be emulated with:
1746 TIMEFORMAT=$'\nreal\t%2lR\nuser\t%2lU\nsys\t%2lS'
1748 G5) How do I get the current directory into my prompt?
1750 Bash provides a number of backslash-escape sequences which are expanded
1751 when the prompt string (PS1 or PS2) is displayed. The full list is in
1754 The \w expansion gives the full pathname of the current directory, with
1755 a tilde (`~') substituted for the current value of $HOME. The \W
1756 expansion gives the basename of the current directory. To put the full
1757 pathname of the current directory into the path without any tilde
1758 subsitution, use $PWD. Here are some examples:
1760 PS1='\w$ ' # current directory with tilde
1761 PS1='\W$ ' # basename of current directory
1762 PS1='$PWD$ ' # full pathname of current directory
1764 The single quotes are important in the final example to prevent $PWD from
1765 being expanded when the assignment to PS1 is performed.
1767 G6) How can I rename "*.foo" to "*.bar"?
1769 Use the pattern removal functionality described in D3. The following `for'
1770 loop will do the trick:
1776 G7) How can I translate a filename from uppercase to lowercase?
1778 The script examples/functions/lowercase, originally written by John DuBois,
1779 will do the trick. The converse is left as an exercise.
1781 G8) How can I write a filename expansion (globbing) pattern that will match
1782 all files in the current directory except "." and ".."?
1784 You must have set the `extglob' shell option using `shopt -s extglob' to use
1789 A solution that works without extended globbing is given in the Unix Shell
1790 FAQ, posted periodically to comp.unix.shell.
1792 Section H: Where do I go from here?
1794 H1) How do I report bugs in bash, and where should I look for fixes and
1797 Use the `bashbug' script to report bugs. It is built and
1798 installed at the same time as bash. It provides a standard
1799 template for reporting a problem and automatically includes
1800 information about your configuration and build environment.
1802 `bashbug' sends its reports to bug-bash@gnu.org, which
1803 is a large mailing list gatewayed to the usenet newsgroup gnu.bash.bug.
1805 Bug fixes, answers to questions, and announcements of new releases
1806 are all posted to gnu.bash.bug. Discussions concerning bash features
1807 and problems also take place there.
1809 To reach the bash maintainers directly, send mail to
1810 bash-maintainers@gnu.org.
1812 H2) What kind of bash documentation is there?
1814 First, look in the doc directory in the bash distribution. It should
1815 contain at least the following files:
1817 bash.1 an extensive, thorough Unix-style manual page
1818 builtins.1 a manual page covering just bash builtin commands
1819 bashref.texi a reference manual in GNU tex`info format
1820 bashref.info an info version of the reference manual
1822 article.ms text of an article written for The Linux Journal
1823 readline.3 a man page describing readline
1825 Postscript, HTML, and ASCII files created from the above source are
1826 available in the documentation distribution.
1828 There is additional documentation available for anonymous FTP from host
1829 ftp.cwru.edu in the `pub/bash' directory.
1831 Cameron Newham and Bill Rosenblatt have written a book on bash, published
1832 by O'Reilly and Associates. The book is based on Bill Rosenblatt's Korn
1833 Shell book. The title is ``Learning the Bash Shell'', and the ISBN number
1834 of the third edition, published in March, 2005, is 0-596-00965-8. Look for
1835 it in fine bookstores near you. This edition of the book has been updated
1838 The GNU Bash Reference Manual has been published as a printed book by
1839 Network Theory Ltd (Paperback, ISBN: 0-9541617-7-7, Nov. 2006). It covers
1840 bash-3.2 and is available from most online bookstores (see
1841 http://www.network-theory.co.uk/bash/manual/ for details). The publisher
1842 will donate $1 to the Free Software Foundation for each copy sold.
1844 Arnold Robbins and Nelson Beebe have written ``Classic Shell Scripting'',
1845 published by O'Reilly. The first edition, with ISBN number 0-596-00595-4,
1846 was published in May, 2005.
1848 Chris F. A. Johnson, a frequent contributor to comp.unix.shell and
1849 gnu.bash.bug, has written ``Shell Scripting Recipes: A Problem-Solution
1850 Approach,'' a new book on shell scripting, concentrating on features of
1851 the POSIX standard helpful to shell script writers. The first edition from
1852 Apress, with ISBN number 1-59059-471-1, was published in May, 2005.
1854 H3) What's coming in future versions?
1856 These are features I hope to include in a future version of bash.
1858 Rocky Bernstein's bash debugger (support is included with bash-3.0)
1860 co-processes, but with a new-style syntax that looks like function declaration
1862 H4) What's on the bash `wish list' for future versions?
1864 These are features that may or may not appear in a future version of bash.
1866 breaking some of the shell functionality into embeddable libraries
1867 a module system like zsh's, using dynamic loading like builtins
1868 a bash programmer's guide with a chapter on creating loadable builtins
1869 a better loadable interface to perl with access to the shell builtins and
1870 variables (contributions gratefully accepted)
1871 ksh93-like `nameref' variables
1872 ksh93-like `xx.yy' variables (including some of the .sh.* variables) and
1873 associated disipline functions
1874 Some of the new ksh93 pattern matching operators, like backreferencing
1876 H5) When will the next release appear?
1878 The next version will appear sometime in 2007. Never make predictions.
1880 This document is Copyright 1995-2006 by Chester Ramey.
1882 Permission is hereby granted, without written agreement and
1883 without license or royalty fees, to use, copy, and distribute
1884 this document for any purpose, provided that the above copyright
1885 notice appears in all copies of this document and that the
1886 contents of this document remain unaltered.