blob: 2723f8f35de90cbf558a07b39c2d6c8b7e1c7735 [file] [log] [blame]
Jari Aaltoccc6cda1996-12-23 17:02:34 +00001This is the Bash FAQ, version 2.1, for Bash version 2.0.
2
3This document contains a set of frequently-asked questions concerning
4Bash, the GNU Bourne-Again Shell. Bash is a freely-available command
5interpreter with advanced features for both interactive use and shell
6programming.
7
8Another good source of basic information about shells is the collection
9of FAQ articles periodically posted to comp.unix.shell.
10
11Questions and comments concerning this document should be sent to
12chet@po.cwru.edu.
13
14This document is available for anonymous FTP with the URL
15
16ftp://slc2.ins.cwru.edu/pub/bash/FAQ
17
18----------
19Contents:
20
21Section A: The Basics
22
231) What is it?
242) What's the latest version?
253) Where can I get it?
264) On what machines will bash run?
275) How can I build bash with gcc?
286) How can I make bash my login shell?
297) I just changed my login shell to bash, and now I can't FTP into my
30 machine. Why not?
318) What's the `POSIX 1003.2 standard'?
329) What is the bash `posix mode'?
33
34Section B: The latest version
35
3610) What's new in version 2.0?
3711) Are there any user-visible incompatibilities between bash-2.0 and
38 bash-1.14.7?
39
40Section C: Differences from other Unix shells
41
4212) How does bash differ from sh, the Bourne shell?
4313) How does bash differ from the Korn shell, version ksh88?
4414) Which new features in ksh-93 are not in bash, and which are?
45
46Section D: Why does bash do some things differently than other Unix shells?
47
4815) Why does bash run a different version of `command' than
49 `which command' says it will?
5016) Why doesn't bash treat brace expansions exactly like csh?
5117) Why doesn't bash have csh variable modifiers?
5218) How can I make my csh aliases work when I convert to bash?
5319) How can I pipe standard output and standard error from one command to
54 another, like csh does with `|&'?
5520) Now that I've converted from ksh to bash, are there equivalents to
56 ksh features like autoloaded functions and the `whence' command?
57
58Section E: How can I get bash to do certain things, and why does bash do
59 things the way it does?
60
6121) Why is the bash builtin `test' slightly different from /bin/test?
6222) Why does bash sometimes say `Broken pipe'?
6323) How can I get bash to read and display eight-bit characters?
6424) How do I write a function `x' to replace builtin command `x', but
65 still invoke the command from within the function?
6625) When I have terminal escape sequences in my prompt, why does bash
67 wrap lines at the wrong column?
6826) How can I find the value of a shell variable whose name is the value
69 of another shell variable?
7027) If I pipe the output of a command into `read variable', why doesn't
71 the output show up in $variable when the read command finishes?
7228) I have a bunch of shell scripts that use backslash-escaped characters
73 in arguments to `echo'. Bash doesn't interpret these characters. Why
74 not, and how can I make it understand them?
7529) Why doesn't a while or for loop get suspended when I type ^Z?
7630) How can I make the bash `time' reserved word print timing output that
77 looks like the output from my system's /usr/bin/time?
78
79Section F: Things to watch out for on certain Unix versions
80
8131) Why can't I use command line editing in my `cmdtool'?
8232) I built bash on Solaris 2. Why do globbing expansions and filename
83 completion chop off the first few characters of each filename?
8433) Why does bash dump core after I interrupt username completion or
85 `~user' tilde expansion on a machine running NIS?
8634) I'm running SVR4.2. Why is the line erased every time I type `@'?
8735) Why does bash report syntax errors when my C News scripts use a
88 redirection before a subshell command?
89
90Section G: Where do I go from here?
91
9236) How do I report bugs in bash, and where should I look for fixes and
93 advice?
9437) What kind of bash documentation is there?
9538) What's coming in future versions?
9639) What's on the bash `wish list'?
9740) When will the next release appear?
98
99----------
100Section A: The Basics
101
1021) What is it?
103
104Bash is a Unix command interpreter (shell). It is an implementation of
105the Posix 1003.2 shell standard, and resembles the Korn and System V
106shells.
107
108Bash contains a number of enhancements over those shells, both
109for interactive use and shell programming. Features geared
110toward interactive use include command line editing, command
111history, job control, aliases, and prompt expansion. Programming
112features include additional variable expansions, shell
113arithmetic, and a number of variables and options to control
114shell behavior.
115
116Bash was originally written by Brian Fox of the Free Software
117Foundation. The current developer and maintainer is Chet Ramey
118of Case Western Reserve University.
119
1202) What's the latest version?
121
122The latest version is 2.0, first made available on December 23, 1996.
123
1243) Where can I get it?
125
126Bash is the GNU project's shell, and so is available from the
127master GNU archive site, prep.ai.mit.edu, and its mirrors. The
128latest version is also available for FTP from slc2.ins.cwru.edu,
129the maintainer's machine. The following URLs tell how to get
130version 2.0:
131
132ftp://prep.ai.mit.edu/pub/gnu/bash-2.0.tar.gz
133ftp://slc2.ins.cwru.edu/pub/dist/bash-2.0.tar.gz
134
135Formatted versions of the documentation are available with the URLs:
136
137ftp://prep.ai.mit.edu/pub/gnu/bash-doc-2.0.tar.gz
138ftp://slc2.ins.cwru.edu/pub/dist/bash-doc-2.0.tar.gz
139
1404) On what machines will bash run?
141
142Bash has been ported to nearly every version of UNIX. All you
143should have to do to build it on a machine for which a port
144exists is to type `configure' and then `make'. The build process
145will attempt to discover the version of UNIX you have and tailor
146itself accordingly, using a script created by GNU autoconf.
147
148More information appears in the file `INSTALL' in the distribution.
149
1505) How can I build bash with gcc?
151
152Bash configures to use gcc by default if it is available. Read the
153file INSTALL in the distribution for more information.
154
1556) How can I make bash my login shell?
156
157Some machines let you use `chsh' to change your login shell. Other
158systems use `passwd -s'. If one of these works for you, that's all
159you need. Note that many systems require the full pathname to a shell
160to appear in /etc/shells before you can make it your login shell. For
161this, you may need the assistance of your friendly local system
162administrator.
163
164If you cannot do this, you can still use bash as your login shell, but
165you need to perform some tricks. The basic idea is to add a command
166to your login shell's startup file to replace your login shell with
167bash.
168
169For example, if your login shell is csh or tcsh, and you have installed
170bash in /usr/gnu/bin/bash, add the following line to ~/.login:
171
172 if ( -f /usr/gnu/bin/bash ) exec /usr/gnu/bin/bash --login
173
174(the `--login' tells bash that it is a login shell).
175
176It's not a good idea to put this command into ~/.cshrc, because every
177csh you run without the `-f' option, even ones started to run csh scripts,
178reads that file. If you must put the command in ~/.cshrc, use something
179like
180
181 if ( $?prompt ) exec /usr/gnu/bin/bash --login
182
183to ensure that bash is exec'd only when the csh is interactive.
184
185If your login shell is sh or ksh, you have to do two things. First, add
186a line similar to the above to ~/.profile:
187
188 [ -f /usr/gnu/bin/bash ] && exec /usr/gnu/bin/bash --login
189
190Next, create an empty file in your home directory named `.bash_profile'.
191The existence of this file will prevent the exec'd bash from trying to
192read ~/.profile, and re-execing itself over and over again. ~/.bash_profile
193is the file bash tries to read initialization commands from when it is
194invoked as a login shell.
195
1967) I just changed my login shell to bash, and now I can't FTP into my
197 machine. Why not?
198
199You must add the full pathname to bash to the file /etc/shells. As
200noted in the answer to the previous question, many systems require
201this before you can make bash your login shell.
202
203Most versions of ftpd use this file to prohibit `special' users
204such as `uucp' and `news' from using FTP.
205
2068) What's the `POSIX 1003.2 standard'?
207
208POSIX is a name originally coined by Richard Stallman for a
209family of open system standards based on UNIX. There are a
210number of aspects of UNIX under consideration for
211standardization, from the basic system services at the system
212call and C library level to applications and tools to system
213administration and management. Each area of standardization is
214assigned to a working group in the 1003 series.
215
216The POSIX Shell and Utilities standard has been developed by IEEE
217Working Group 1003.2 (POSIX.2). It concentrates on the command
218interpreter interface and utility programs commonly executed from
219the command line or by other programs. An initial version of the
220standard has been approved and published by the IEEE, and work is
221currently underway to update it.
222
223Bash is concerned with the aspects of the shell's behavior
224defined by POSIX.2. The shell command language has of course
225been standardized, including the basic flow control and program
226execution constructs, I/O redirection and pipelining, argument
227handling, variable expansion, and quoting.
228
229The `special' builtins, which must be implemented as part of the
230shell to provide the desired functionality, are specified as
231being part of the shell; examples of these are `eval' and
232`export'. Other utilities appear in the sections of POSIX.2 not
233devoted to the shell which are commonly (and in some cases must
234be) implemented as builtin commands, such as `read' and `test'.
235POSIX.2 also specifies aspects of the shell's interactive
236behavior as part of the UPE, including job control and command
237line editing. Only vi-style line editing commands have been
238standardized; emacs editing commands were left out due to
239objections.
240
2419) What is the bash `posix mode'?
242
243Although bash is an implementation of the POSIX.2 shell
244specification, there are areas where the bash default behavior
245differs from that spec. The bash `posix mode' changes the bash
246behavior in these areas so that it obeys the spec more closely.
247
248Posix mode is entered by starting bash with the --posix option or
249executing `set -o posix' after bash is running.
250
251The specific aspects of bash which change when posix mode is
252active are listed in the file CWRU/POSIX.NOTES in the bash
253distribution. They are also listed in a section in the Bash
254Reference Manual.
255
256Section B: The latest version
257
25810) What's new in version 2.0?
259
260This version contains extensive changes and new features. Here's a
261short list:
262
263new `time' reserved word to time pipelines, shell builtins, and
264 shell functions
265one-dimensional arrays with a new compound assignment statement,
266 appropriate expansion constructs and modifications to some
267 of the builtins (read, declare, etc.) to use them
268new quoting syntaxes for ANSI-C string expansion and locale-specific
269 string translation
270new expansions to do substring extraction, pattern replacement, and
271 indirect variable expansion
272new builtins: `disown' and `shopt'
273new variables: HISTIGNORE, SHELLOPTS, PIPESTATUS, DIRSTACK, GLOBIGNORE,
274 MACHTYPE, BASH_VERSINFO
275special handling of many unused or redundant variables removed
276 (e.g., $notify, $glob_dot_filenames, $no_exit_on_failed_exec)
277dynamic loading of new builtin commands; many loadable examples provided
278new prompt expansions: \a, \e, \n, \H, \T, \@, \v, \V
279history and aliases available in shell scripts
280new readline variables: enable-keypad, mark-directories, input-meta,
281 visible-stats, disable-completion, comment-begin
282new readline commands to manipulate the mark and operate on the region
283new readline emacs mode commands and bindings for ksh-88 compatibility
284updated and extended builtins
285new DEBUG trap
286expanded (and now documented) restricted shell mode
287
288implementation stuff:
289autoconf-based configuration
290nearly all of the bugs reported since version 1.14 have been fixed
291most builtins converted to use builtin `getopt' for consistency
292most builtins use -p option to display output in a reusable form
293 (for consistency)
294grammar tighter and smaller (66 reduce-reduce conflicts gone)
295lots of code now smaller and faster
296test suite greatly expanded
297
29811) Are there any user-visible incompatibilities between bash-2.0 and
299 bash-1.14.7?
300
301There are a few incompatibilities between version 1.14.7 and version 2.0.
302They are detailed in the file COMPAT in the bash-2.0 distribution.
303
304Section C: Differences from other Unix shells
305
30612) How does bash differ from sh, the Bourne shell?
307
308This is a non-comprehensive list of features that differentiate bash
309from the SVR4.2 shell. The bash manual page explains these more
310completely.
311
312Things bash has that sh does not:
313 long invocation options
314 `!' reserved word to invert pipeline return value
315 `time' reserved word to time pipelines and shell builtins
316 the `function' reserved word
317 the select compound command and reserved word
318 new $'...' and $"..." quoting
319 the $(...) form of command substitution
320 the ${#param} parameter value length operator
321 the ${!param} indirect parameter expansion operator
322 the ${param:length[:offset]} parameter substring operator
323 the ${param/pat[/string]} parameter pattern substitution operator
324 expansions to perform substring removal (${p%[%]w}, ${p#[#]w})
325 expansion of positional parameters beyond $9 with ${num}
326 variables: BASH, BASH_VERSION, BASH_VERSINFO, UID, EUID, REPLY,
327 TIMEFORMAT, PPID, PWD, OLDPWD, SHLVL, RANDOM, SECONDS,
328 LINENO, HISTCMD, HOSTTYPE, OSTYPE, MACHTYPE, HOSTNAME,
329 ENV, PS3, PS4, DIRSTACK, PIPESTATUS, HISTSIZE, HISTFILE,
330 HISTFILESIZE, HISTCONTROL, HISTIGNORE, GLOBIGNORE,
331 PROMPT_COMMAND, FCEDIT, FIGNORE, IGNOREEOF, INPUTRC,
332 SHELLOPTS, OPTERR, HOSTFILE, TMOUT, histchars, auto_resume
333 DEBUG trap
334 variable arrays with new compound assignment syntax
335 redirections: <>, &>, >|
336 prompt string special char translation and variable expansion
337 auto-export of modified values of variables in initial environment
338 command search finds functions before builtins
339 bash return builtin will exit a file sourced with `.'
340 builtins: cd -/-L/-P, exec -l/-c/-a, echo -e/-E, hash -p.
341 export -n/-f/-p/name=value, pwd -L/-P, read -e/-p/-a,
342 readonly -a/-f/name=value, trap -l, set +o,
343 set -b/-m/-o option/-h/-p/-B/-C/-H/-P,
344 unset -f/-v, ulimit -m/-p/-u,
345 type -a/-p/-t, suspend -f, kill -n,
346 test -o optname/s1 == s2/s1 < s2/s1 > s2/-nt/-ot/-ef/-O/-G/-S
347 bash reads ~/.bashrc for interactive shells, $ENV for non-interactive
348 bash restricted shell mode is more extensive
349 bash allows functions and variables with the same name
350 brace expansion
351 tilde expansion
352 arithmetic expansion with $((...)) and `let' builtin
353 process substitution
354 aliases and alias/unalias builtins
355 local variables in functions and `local' builtin
356 readline and command-line editing
357 command history and history/fc builtins
358 csh-like history expansion
359 other new bash builtins: bind, command, builtin, declare/typeset,
360 dirs, enable, fc, help, history, logout,
361 popd, pushd, disown, shopt
362 exported functions
363 filename generation when using output redirection (command >a*)
364 variable assignments preceding commands affect only that command,
365 even for builtins and functions
366 posix mode
367
368Things sh has that bash does not:
369 uses variable SHACCT to do shell accounting
370 includes `stop' builtin (bash can use alias stop='kill -s STOP')
371 `newgrp' builtin
372 turns on job control if called as `jsh'
373 ulimit attempts to set both soft & hard limits if -S/-H not given
374 $TIMEOUT (like bash $TMOUT)
375 `^' is a synonym for `|'
376 new SVR4.2 sh builtins: mldmode, priv
377
378Implementation differences:
379 redirection to/from compound commands causes sh to create a subshell
380 bash does not allow unbalanced quotes; sh silently inserts them at EOF
381 bash does not mess with signal 11
382 sh sets (euid, egid) to (uid, gid) if -p not supplied and uid < 100
383 bash splits only the results of expansions on IFS, using POSIX.2
384 field splitting rules; sh splits all words on IFS
385 sh does not allow MAILCHECK to be unset (?)
386 sh does not allow traps on SIGALRM or SIGCHLD
387 bash allows multiple option arguments when invoked (e.g. -x -v);
388 sh allows only a single option argument (`sh -x -v' attempts
389 to open a file named `-v', and, on SunOS 4.1.4, dumps core)
390 sh exits a script if any builtin fails; bash exits only if one of
391 the POSIX.2 `special' builtins fails
392
39313) How does bash differ from the Korn shell, version ksh88?
394
395Things bash has or uses that ksh88 does not:
396 long invocation options
397 `!' reserved word
398 posix mode and posix conformance
399 command hashing
400 tilde expansion for assignment statements that look like $PATH
401 process substitution with named pipes if /dev/fd is not available
402 the ${!param} indirect parameter expansion operator
403 the ${param:length[:offset]} parameter substring operator
404 the ${param/pat[/string]} parameter pattern substitution operator
405 variables: BASH, BASH_VERSION, BASH_VERSINFO, UID, EUID, SHLVL,
406 TIMEFORMAT, HISTCMD, HOSTTYPE, OSTYPE, MACHTYPE,
407 HISTFILESIZE, HISTIGNORE, HISTCONTROL, PROMPT_COMMAND,
408 IGNOREEOF, FIGNORE, INPUTRC, HOSTFILE, DIRSTACK,
409 PIPESTATUS, HOSTNAME, OPTERR, SHELLOPTS, GLOBIGNORE,
410 histchars, auto_resume
411 prompt expansion with backslash escapes and command substitution
412 redirection: &> (stdout and stderr)
413 more extensive and extensible editing and completion
414 builtins: bind, builtin, command, declare, dirs, echo -e/-E, enable,
415 exec -l/-c/-a, fc -s, export -n/-f/-p, hash, help, history,
416 jobs -x/-r/-s, kill -s/-n/-l, local, logout, popd, pushd,
417 read -e/-p/-a, readonly -a/-n/-f/-p, set -o braceexpand/
418 -o histexpand/-o interactive-comments/-o notify/-o physical/
419 -o posix/-o hashall/-o onecmd/-h/-B/-C/-b/-H/-P, set +o,
420 suspend, trap -l, type, typeset -a/-F/-p, ulimit -u,
421 umask -S, alias -p, shopt, disown
422 `!' csh-style history expansion
423
424Things ksh88 has or uses that bash does not:
425 new version of test: [[...]]
426 tracked aliases
427 $(<file)
428 variables: ERRNO, FPATH, COLUMNS, LINES, EDITOR, VISUAL
429 extended pattern matching with egrep-style pattern lists
430 co-processes (|&, >&p, <&p)
431 weirdly-scoped functions
432 typeset +f to list all function names without definitions
433 text of command history kept in a file, not memory
434 builtins: alias -x, cd old new, fc -e -, newgrp, print,
435 read -p/-s/-u/var?prompt, set -A/-o gmacs/
436 -o bgnice/-o markdirs/-o nolog/-o trackall/-o viraw/-s,
437 typeset -H/-L/-R/-A/-ft/-fu/-fx/-l/-u/-t, whence
438
439Implementation differences:
440 ksh runs last command of a pipeline in parent shell context
441 ksh ulimit sets hard and soft limits by default
442 bash has brace expansion by default (ksh88 compile-time option)
443 bash has fixed startup file for all interactive shells; ksh reads $ENV
444 bash has exported functions
445 bash command search finds functions before builtins
446
44714) Which new features in ksh-93 are not in bash, and which are?
448
449New things in ksh-93 not in bash-2.0:
450 associative arrays
451 floating point arithmetic
452 ++, --, comma arithmetic operators
453 math library functions
454 ${!name[sub]} name of subscript for associative array
455 ${!prefix*} and {!prefix@} variable name prefix expansions
456 `.' is allowed in variable names to create a hierarchical namespace
457 more extensive compound assignment syntax
458 discipline functions
459 `sleep' and `getconf' builtins (bash has loadable versions)
460 typeset -n and `nameref' variables
461 KEYBD trap
462 variables: .sh.edchar, .sh.edmode, .sh.edcol, .sh.edtext, HISTEDIT,
463 .sh.version, .sh.name, .sh.subscript, .sh.value
464 backreferences in pattern matching
465 print -f and printf (bash has loadable versions)
466 `fc' has been renamed to `hist'
467 read -t/-d
468 `.' can execute shell functions
469 ENV processed only for interactive shells
470
471New things in ksh-93 present in bash-2.0:
472 ?: arithmetic operator
473 expansions: ${!param}, ${param:len[:offset]}, ${param/pat[/str]}
474 compound array assignment
475 the `!' reserved word
476 loadable builtins -- but ksh uses `builtin' while bash uses `enable'
477 `command', `builtin', `disown' builtins
478 new $'...' and $"..." quoting
479 FIGNORE (but bash uses GLOBIGNORE), HISTCMD
480 set -o notify/-C
481 changes to kill builtin
482 read -A (bash uses read -a)
483 trap -p
484 exec -c/-a
485 `.' restores the positional parameters when it completes
486 POSIX.2 `test'
487 umask -S
488 unalias -a
489 command and arithmetic substitution performed on PS1, PS4, and ENV
490 command name completion
491
492Section D: Why does bash do some things differently than other Unix shells?
493
49415) Why does bash run a different version of `command' than
495 `which command' says it will?
496
497`which' is actually a csh script that assumes you're running csh.
498It reads the csh startup files from your home directory and uses
499those to determine which `command' will be invoked. Since bash
500doesn't use any of those startup files, there's a good chance
501that your bash environment differs from your csh environment.
502
50316) Why doesn't bash treat brace expansions exactly like csh?
504
505The only difference between bash and csh brace expansion is that
506bash requires a brace expression to contain at least one unquoted
507comma if it is to be expanded. Any brace-surrounded word not
508containing an unquoted comma is left unchanged by the brace
509expansion code. This affords the greatest degree of sh
510compatibility.
511
512Bash, ksh, zsh, and pd-ksh all implement brace expansion this way.
513
51417) Why doesn't bash have csh variable modifiers?
515
516Posix has specified a more powerful, albeit somewhat more cryptic,
517mechanism cribbed from ksh, and bash implements it.
518
519${parameter%word}
520 Remove smallest suffix pattern. The WORD is expanded to produce
521 a pattern. It then expands to the value of PARAMETER, with the
522 smallest portion of the suffix matched by the pattern deleted.
523
524 x=file.c
525 echo ${x%.c}.o
526 -->file.o
527
528${parameter%%word}
529
530 Remove largest suffix pattern. The WORD is expanded to produce
531 a pattern. It then expands to the value of PARAMETER, with the
532 largest portion of the suffix matched by the pattern deleted.
533
534 x=posix/src/std
535 echo ${x%%/*}
536 -->posix
537
538${parameter#word}
539 Remove smallest prefix pattern. The WORD is expanded to produce
540 a pattern. It then expands to the value of PARAMETER, with the
541 smallest portion of the prefix matched by the pattern deleted.
542
543 x=$HOME/src/cmd
544 echo ${x#$HOME}
545 -->/src/cmd
546
547${parameter##word}
548 Remove largest prefix pattern. The WORD is expanded to produce
549 a pattern. It then expands to the value of PARAMETER, with the
550 largest portion of the prefix matched by the pattern deleted.
551
552 x=/one/two/three
553 echo ${x##*/}
554 -->three
555
556
557Given
558 a=/a/b/c/d
559 b=b.xxx
560
561 csh bash result
562 --- ---- ------
563 $a:h ${a%/*} /a/b/c
564 $a:t ${a##*/} d
565 $b:r ${b%.*} b
566 $b:e ${b##*.} xxx
567
568
56918) How can I make my csh aliases work when I convert to bash?
570
571Bash uses a different syntax to support aliases than csh does.
572The details can be found in the documentation. We have provided
573a shell script which does most of the work of conversion for you;
574this script can be found in ./examples/misc/alias-conv.sh. Here is
575how you use it:
576
577Start csh in the normal way for you. (e.g., `csh')
578
579Pipe the output of `alias' through `alias-conv.sh', saving the
580results into `bash_aliases':
581
582 alias | alias-conv.sh >bash_aliases
583
584Edit `bash_aliases', carefully reading through any created
585functions. You will need to change the names of some csh specific
586variables to the bash equivalents. The script converts $cwd to
587$PWD, $term to $TERM, $home to $HOME, $user to $USER, and $prompt
588to $PS1. You may also have to add quotes to avoid unwanted
589expansion.
590
591For example, the csh alias:
592
593 alias cd 'cd \!*; echo $cwd'
594
595is converted to the bash function:
596
597 cd () { command cd "$@"; echo $PWD ; }
598
599The only thing that needs to be done is to quote $PWD:
600
601 cd () { command cd "$@"; echo "$PWD" ; }
602
603Merge the edited file into your ~/.bashrc.
604
605There is an additional, more ambitious, script in
606examples/misc/cshtobash that attempts to convert your entire csh
607environment to its bash equivalent. This script can be run as
608simply `cshtobash' to convert your normal interactive
609environment, or as `cshtobash ~/.login' to convert your login
610environment.
611
61219) How can I pipe standard output and standard error from one command to
613 another, like csh does with `|&'?
614
615Use
616 command 2>&1 | command2
617
618The key is to remember that piping is performed before redirection, so
619file descriptor 1 points to the pipe when it is duplicated onto file
620descriptor 2.
621
62220) Now that I've converted from ksh to bash, are there equivalents to
623 ksh features like autoloaded functions and the `whence' command?
624
625There are features in ksh-88 that do not have direct bash equivalents.
626Most, however, can be emulated with very little trouble.
627
628ksh-88 feature Bash equivalent
629-------------- ---------------
630[[...]] can usually use [...]; minor differences (no
631 pattern matching, for one)
632compiled-in aliases set up aliases in .bashrc; some ksh aliases are
633 bash builtins (hash, history, type)
634$(<file) $(cat file)
635extended patterns no good substitute
636coprocesses named pipe pairs (one for read, one for write)
637typeset +f declare -F
638cd, print, whence function substitutes in examples/functions/kshenv
639autoloaded functions examples/functions/autoload is the same as typeset -fu
640read var?prompt read -p prompt var
641
642Section E: How can I get bash to do certain things, and why does bash do
643 things the way it does?
644
64521) Why is the bash builtin `test' slightly different from /bin/test?
646
647The specific example used here is [ ! x -o x ], which is false.
648
649Bash's builtin `test' implements the Posix.2 spec, which can be
650summarized as follows (the wording is due to David Korn):
651
652Here is the set of rules for processing test arguments.
653
654 0 Args: False
655 1 Arg: True iff argument is not null.
656 2 Args: If first arg is !, True iff second argument is null.
657 If first argument is unary, then true if unary test is true
658 Otherwise error.
659 3 Args: If second argument is a binary operator, do binary test of $1 $3
660 If first argument is !, negate two argument test of $2 $3
661 If first argument is `(' and third argument is `)', do the
662 one-argument test of the second argument.
663 Otherwise error.
664 4 Args: If first argument is !, negate three argument test of $2 $3 $4.
665 Otherwise unspecified
666 5 or more Args: unspecified. (Historical shells would use their
667 current algorithm).
668
669The operators -a and -o are considered binary operators for the purpose
670of the 3 Arg case.
671
672As you can see, the test becomes (not (x or x)), which is false.
673
67422) Why does bash sometimes say `Broken pipe'?
675
676If a sequence of commands appears in a pipeline, and one of the
677reading commands finishes before the writer has finished, the
678writer receives a SIGPIPE signal. Many other shells special-case
679SIGPIPE as an exit status in the pipeline and do not report it.
680For example, in:
681
682 ps -aux | head
683
684`head' can finish before `ps' writes all of its output, and ps
685will try to write on a pipe without a reader. In that case, bash
686will print `Broken pipe' to stderr when ps is killed by a
687SIGPIPE.
688
68923) How can I get bash to read and display eight-bit characters?
690
691This is a process requiring several steps.
692
693First, you must ensure that the `physical' data path is a full eight
694bits. For xterms, for example, the `vt100' resources `eightBitInput'
695and `eightBitOutput' should be set to `true'.
696
697Once you have set up an eight-bit path, you must tell the kernel and
698tty driver to leave the eighth bit of characters alone when processing
699keyboard input. Use `stty' to do this:
700
701 stty cs8 -istrip -parenb
702
703For old BSD-style systems, you can use
704
705 stty pass8
706
707You may also need
708
709 stty even odd
710
711Finally, you need to tell readline that you will be inputting and
712displaying eight-bit characters. You use readline variables to do
713this. These variables can be set in your .inputrc or using the bash
714`bind' builtin. Here's an example using `bind':
715
716 bash$ bind 'set convert-meta off'
717 bash$ bind 'set meta-flag on'
718 bash$ bind 'set output-meta on'
719
720The `set' commands between the single quotes may also be placed
721in ~/.inputrc.
722
72324) How do I write a function `x' to replace builtin command `x', but
724 still invoke the command from within the function?
725
726This is why the `command' and `builtin' builtins exist. The
727`command' builtin executes the command supplied as its first
728argument, skipping over any function defined with that name. The
729`builtin' builtin executes the builtin command given as its first
730argument directly.
731
732For example, to write a function to replace `cd' that writes the
733hostname and current directory to an xterm title bar, use
734something like the following:
735
736 cd()
737 {
738 builtin cd "$@" && xtitle "$HOST: $PWD"
739 }
740
741This could also be written using `command' instead of `builtin';
742the version above is marginally more efficient.
743
74425) When I have terminal escape sequences in my prompt, why does bash
745 wrap lines at the wrong column?
746
747Readline, the line editing library that bash uses, does not know
748that the terminal escape sequences do not take up space on the
749screen. The redisplay code assumes, unless told otherwise, that
750each character in the prompt is a `printable' character that
751takes up one character position on the screen.
752
753You can use the bash prompt expansion facility (see the PROMPTING
754section in the manual page) to tell readline that sequences of
755characters in the prompt strings take up no screen space.
756
757Use the \[ escape to begin a sequence of non-printing characters,
758and the \] escape to signal the end of such a sequence.
759
76026) How can I find the value of a shell variable whose name is the value
761 of another shell variable?
762
763Bash-2.0 supports this directly. You can use
764
765 ${!var}
766
767For example, the following sequence of commands will echo `z':
768
769 var1=var2
770 var2=z
771 echo ${!var1}
772
773For sh compatibility, use the `eval' builtin. The important
774thing to remember is that `eval' expands the arguments you give
775it again, so you need to quote the parts of the arguments that
776you want `eval' to act on.
777
778For example, this expression prints the value of the last positional
779parameter:
780
781 eval echo \"\$\{$#\}\"
782
783The expansion of the quoted portions of this expression will be
784deferred until `eval' runs, while the `$#' will be expanded
785before `eval' is executed. In bash-2.0,
786
787 echo ${!#}
788
789does the same thing.
790
79127) If I pipe the output of a command into `read variable', why doesn't
792 the output show up in $variable when the read command finishes?
793
794This has to do with the parent-child relationship between Unix
795processes.
796
797Each element of a pipeline runs in a separate process, a child of
798the shell running the pipeline. A subprocess cannot affect its
799parent's environment. When the `read' command sets the variable
800to the input, that variable is set only in the subshell, not the
801parent shell. When the subshell exits, the value of the variable
802is lost.
803
804Many pipelines that end with `read variable' can be converted
805into command substitutions, which will capture the output of
806a specified command. The output can then be assigned to a
807variable:
808
809 grep ^gnu /usr/lib/news/active | wc -l | read ngroup
810
811can be converted into
812
813 ngroup=$(grep ^gnu /usr/lib/news/active | wc -l)
814
815This does not, unfortunately, work to split the text among
816multiple variables, as read does when given multiple variable
817arguments. If you need to do this, you can either use the
818command substitution above to read the output into a variable
819and chop up the variable using the bash pattern removal
820expansion operators or use some variant of the following
821approach.
822
823Say /usr/local/bin/ipaddr is the following shell script:
824
825#! /bin/sh
826host `hostname` | awk '/address/ {print $NF}'
827
828Instead of using
829
830 /usr/local/bin/ipaddr | read A B C D
831
832to break the local machine's IP address into separate octets, use
833
834 OIFS="$IFS"
835 IFS=.
836 set -- $(/usr/local/bin/ipaddr)
837 IFS="$OIFS"
838 A="$1" B="$2" C="$3" D="$4"
839
840Beware, however, that this will change the shell's positional
841parameters. If you need them, you should save them before doing
842this.
843
844This is the general approach -- in most cases you will not need to
845set $IFS to a different value.
846
84728) I have a bunch of shell scripts that use backslash-escaped characters
848 in arguments to `echo'. Bash doesn't interpret these characters. Why
849 not, and how can I make it understand them?
850
851This is the behavior of echo on most Unix System V machines.
852
853The bash builtin `echo' is modelled after the 9th Edition
854Research Unix version of `echo'. It does not interpret
855backslash-escaped characters in its argument strings by default;
856it requires the use of the -e option to enable the
857interpretation. The System V echo provides no way to disable the
858special characters; the bash echo has a -E option to disable
859them.
860
861There is a configuration option that will make bash behave like
862the System V echo and interpret things like `\t' by default. Run
863configure with the --enable-usg-echo-default option to turn this
864on. Be aware that this will cause some of the tests run when you
865type `make tests' to fail.
866
86729) Why doesn't a while or for loop get suspended when I type ^Z?
868
869This is a consequence of how job control works on Unix. The only
870thing that can be suspended is the process group. This is a single
871command or pipeline of commands that the shell forks and executes.
872
873When you run a while or for loop, the only thing that the shell forks
874and executes are any commands in the while loop test and commands in
875the loop bodies. These, therefore, are the only things that can be
876suspended when you type ^Z.
877
878If you want to be able to stop the entire loop, you need to put it
879within parentheses, which will force the loop into a subshell that
880may be stopped (and subsequently restarted) as a single unit.
881
88230) How can I make the bash `time' reserved word print timing output that
883 looks like the output from my system's /usr/bin/time?
884
885The bash command timing code looks for a variable `TIMEFORMAT' and
886uses its value as a format string to decide how to display the
887timing statistics.
888
889The value of TIMEFORMAT is a string with `%' escapes expanded in a
890fashion similar in spirit to printf(3). The manual page explains
891the meanings of the escape sequences in the format string.
892
893If TIMEFORMAT is not set, bash acts as if the following assignment had
894been performed:
895
896 TIMEFORMAT=$'\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS'
897
898The POSIX.2 default time format (used by `time -p command') is
899
900 TIMEFORMAT=$'real %2R\nuser %2U\nsys %2S'
901
902The BSD /usr/bin/time format can be emulated with:
903
904 TIMEFORMAT=$'\t%1R real\t%1U user\t%1S sys'
905
906The System V /usr/bin/time format can be emulated with:
907
908 TIMEFORMAT=$'\nreal\t%1R\nuser\t%1U\nsys\t%1S'
909
910The ksh format can be emulated with:
911
912 TIMEFORMAT=$'\nreal\t%2lR\nuser\t%2lU\nsys\t%2lS'
913
914Section F: Things to watch out for on certain Unix versions
915
91631) Why can't I use command line editing in my `cmdtool'?
917
918The problem is `cmdtool' and bash fighting over the input. When
919scrolling is enabled in a cmdtool window, cmdtool puts the tty in
920`raw mode' to permit command-line editing using the mouse for
921applications that cannot do it themselves. As a result, bash and
922cmdtool each try to read keyboard input immediately, with neither
923getting enough of it to be useful.
924
925This mode also causes cmdtool to not implement many of the
926terminal functions and control sequences appearing in the
927`sun-cmd' termcap entry. For a more complete explanation, see
928that file examples/suncmd.termcap in the bash distribution.
929
930`xterm' is a better choice, and gets along with bash much more
931smoothly.
932
933If you must use cmdtool, you can use the termcap description in
934examples/suncmd.termcap. Set the TERMCAP variable to the terminal
935description contained in that file, i.e.
936
937TERMCAP='Mu|sun-cmd:am:bs:km:pt:li#34:co#80:cl=^L:ce=\E[K:cd=\E[J:rs=\E[s:'
938
939Then export TERMCAP and start a new cmdtool window from that shell.
940The bash command-line editing should behave better in the new
941cmdtool. If this works, you can put the assignment to TERMCAP
942in your bashrc file.
943
94432) I built bash on Solaris 2. Why do globbing expansions and filename
945 completion chop off the first few characters of each filename?
946
947This is the consequence of building bash on SunOS 5 and linking
948with the libraries in /usr/ucblib, but using the definitions
949and structures from files in /usr/include.
950
951The actual conflict is between the dirent structure in
952/usr/include/dirent.h and the struct returned by the version of
953`readdir' in libucb.a (a 4.3-BSD style `struct direct').
954
955Make sure you've got /usr/ccs/bin ahead of /usr/ucb in your $PATH
956when configuring and building bash. This will ensure that you
957use /usr/ccs/bin/cc or acc instead of /usr/ucb/cc and that you
958link with libc before libucb.
959
960If you have installed the Sun C compiler, you may also need to
961put /usr/ccs/bin and /opt/SUNWspro/bin into your $PATH before
962/usr/ucb.
963
96433) Why does bash dump core after I interrupt username completion or
965 `~user' tilde expansion on a machine running NIS?
966
967This is a famous and long-standing bug in the SunOS YP (sorry, NIS)
968client library, which is part of libc.
969
970The YP library code keeps static state -- a pointer into the data
971returned from the server. When YP initializes itself (setpwent),
972it looks at this pointer and calls free on it if it's non-null.
973So far, so good.
974
975If one of the YP functions is interrupted during getpwent (the
976exact function is interpretwithsave()), and returns NULL, the
977pointer is freed without being reset to NULL, and the function
978returns. The next time getpwent is called, it sees that this
979pointer is non-null, calls free, and the bash free() blows up
980because it's being asked to free freed memory.
981
982The traditional Unix mallocs allow memory to be freed multiple
983times; that's probably why this has never been fixed. You can
984run configure with the `--without-gnu-malloc' option to use
985the C library malloc and avoid the problem.
986
98734) I'm running SVR4.2. Why is the line erased every time I type `@'?
988
989The `@' character is the default `line kill' character in most
990versions of System V, including SVR4.2. You can change this
991character to whatever you want using `stty'. For example, to
992change the line kill character to control-u, type
993
994 stty kill ^U
995
996where the `^' and `U' can be two separate characters.
997
99835) Why does bash report syntax errors when my C News scripts use a
999 redirection before a subshell command?
1000
1001The actual command in question is something like
1002
1003 < file ( command )
1004
1005According to the grammar given in the POSIX.2 standard, this construct
1006is, in fact, a syntax error. Redirections may only precede `simple
1007commands'. A subshell construct such as the above is one of the shell's
1008`compound commands'. A redirection may only follow a compound command.
1009
1010The file CWRU/sh-redir-hack in the bash-2.0 distribution is an
1011(unofficial) patch to parse.y that will modify the grammar to
1012support this construct. It will not apply with `patch'; you must
1013modify parse.y by hand. Note that if you apply this, you must
1014recompile with -DREDIRECTION_HACK. This introduces a large
1015number of reduce/reduce conflicts into the shell grammar.
1016
1017Section G: Where do I go from here?
1018
101936) How do I report bugs in bash, and where should I look for fixes and
1020 advice?
1021
1022Use the `bashbug' script to report bugs. It is built and
1023installed at the same time as bash. It provides a standard
1024template for reporting a problem and automatically includes
1025information about your configuration and build environment.
1026
1027`bashbug' sends its reports to bug-bash@prep.ai.mit.edu, which
1028is a large mailing list gatewayed to the usenet newsgroup gnu.bash.bug.
1029
1030Bug fixes, answers to questions, and announcements of new releases
1031are all posted to gnu.bash.bug. Discussions concerning bash features
1032and problems also take place there.
1033
1034To reach the bash maintainers directly, send mail to
1035bash-maintainers@prep.ai.mit.edu.
1036
103737) What kind of bash documentation is there?
1038
1039First, look in the doc directory in the bash distribution. It should
1040contain at least the following files:
1041
1042bash.1 an extensive, thorough Unix-style manual page
1043builtins.1 a manual page covering just bash builtin commands
1044bashref.texi a reference manual in GNU info format
1045bash.html an HTML version of the manual page
1046bashref.html an HTML version of the reference manual
1047FAQ this file
1048article.ms text of an article written for The Linux Journal
1049readline.3 a man page describing readline
1050
1051Postscript files created from the above source are available in
1052the documentation distribution.
1053
1054There is additional documentation available for anonymous FTP from host
1055slc2.ins.cwru.edu in the `pub/bash' directory.
1056
1057Cameron Newham and Bill Rosenblatt have written a book on bash, published
1058by O'Reilly and Associates. The book is based on Bill Rosenblatt's Korn
1059Shell book. The title is ``Learning the Bash Shell''. The ISBN number is
10601-56592-147-X. Look for it in fine bookstores near you. This book covers
1061bash-1.14, but has an appendix describing some of the new features in
1062bash-2.0.
1063
106438) What's coming in future versions?
1065
1066These are features I plan to include in a future version of bash.
1067
1068POSIX.2-style globbing character classes ([:alpha:], [:alnum:], etc.)
1069a bash debugger (an incomplete, untested version is included with bash-2.0)
1070
107139) What's on the bash `wish list' for future versions?
1072
1073These are features that may or may not appear in a future version of bash.
1074
1075Programmable completion a la zsh
1076menu completion a la tcsh
1077the ksh [[...]] extended test command
1078the ksh egrep-style extended pattern matching operators
1079associative arrays (not really all that hard)
1080breaking some of the shell functionality into embeddable libraries
1081better internationalization using GNU `gettext'
1082an option to use external files for the long `help' text
1083timeouts for the `read' builtin
1084the ksh-93 ${!prefix*} and ${!prefix@} operators
1085arithmetic ++ and -- prefix and postfix operators
1086
108740) When will the next release appear?
1088
1089The next version will appear sometime in 1997. Never make predictions.
1090
1091
1092This document is Copyright 1995, 1996 by Chester Ramey.
1093
1094Permission is hereby granted, without written agreement and
1095without license or royalty fees, to use, copy, and distribute
1096this document for any purpose, provided that the above copyright
1097notice appears in all copies of this document and that the
1098contents of this document remain unaltered.