Movatterモバイル変換


[0]ホーム

URL:


faqs.org

[gnu.bash.bug] BASH Frequently-Asked Questions (FAQ version 3.36)

Font:

    Search the FAQ Archives

3 -A -B -C -D -E -F -G -H -I -J -K -L -M
N -O -P -Q -R -S -T -U -V -W -X -Y -Z
faqs.org - Internet FAQ Archives

[gnu.bash.bug] BASH Frequently-Asked Questions (FAQ version 3.36)


[Usenet FAQs |Web FAQs |Documents |RFC Index |Cities ]
faqs.org
Archive-name: unix-faq/shell/bash
Posting-Frequency: monthly
Submitted-By: chet@po.cwru.edu (Chet Ramey)
Last-Modified: Fri May 11 16:18:55 EDT 2007
FAQ-Version: 3.36
Bash-Version: 3.2
URL: ftp://ftp.cwru.edu/pub/bash/FAQ
Maintainer: chet@po.cwru.edu (Chet Ramey)

comp.unix.questions,comp.answers,news.answersSubject: [gnu.bash.bug] BASH Frequently-Asked Questions (FAQ version 3.36)Supersedes: <bash_1194966000@usenet.ins.cwru.edu>Followup-To: posterDate: 14 Dec 2007 15:00:00 GMTOrganization: Case Western Reserve UniversityLines: 1886Approved: news-answers-request@MIT.EDUExpires: 27 Jan 2008 15:00:00 GMTMessage-ID: <bash_1197644400@usenet.ins.cwru.edu>Reply-To:chet@po.cwru.eduNNTP-Posting-Host: caleb.ins.cwru.eduX-Trace: eeyore.INS.cwru.edu 1197644400 8386 129.22.8.211 (14 Dec 2007 15:00:00 GMT)X-Complaints-To: abuse@po.cwru.eduNNTP-Posting-Date: 14 Dec 2007 15:00:00 GMTSummary: A's to Q's about BASH, the Bourne-Again SHellOriginator: chet@caleb.ins.cwru.eduXref: cs.uu.nl comp.unix.shell:221979 comp.unix.questions:196500 comp.answers:65510 news.answers:314179ftp://ftp.cwru.edu/pub/bash/FAQThe Bash home page ishttp://cnswww.cns.cwru.edu/~chet/bash/bashtop.html----------Contents:Section A:  The BasicsA1) What is it?A2) What's the latest version?A3) Where can I get it?A4) On what machines will bash run?A5) Will bash run on operating systems other than Unix?A6) How can I build bash with gcc?A7) How can I make bash my login shell?A8) I just changed my login shell to bash, and now I can't FTP into my    machine.  Why not?A9) What's the `POSIX Shell and Utilities standard'?A10) What is the bash `posix mode'?Section B:  The latest versionB1) What's new in version 3.2?B2) Are there any user-visible incompatibilities between bash-3.2 and    bash-2.05b?Section C:  Differences from other Unix shellsC1) How does bash differ from sh, the Bourne shell?C2) How does bash differ from the Korn shell, version ksh88?C3) Which new features in ksh-93 are not in bash, and which are?Section D:  Why does bash do some things differently than other Unix shells?D1) Why does bash run a different version of `command' than    `which command' says it will?D2) Why doesn't bash treat brace expansions exactly like csh?D3) Why doesn't bash have csh variable modifiers?D4) How can I make my csh aliases work when I convert to bash?D5) How can I pipe standard output and standard error from one command to    another, like csh does with `|&'?D6) Now that I've converted from ksh to bash, are there equivalents to    ksh features like autoloaded functions and the `whence' command?Section E:  Why does bash do certain things the way it does?E1) Why is the bash builtin `test' slightly different from /bin/test?E2) Why does bash sometimes say `Broken pipe'?E3) When I have terminal escape sequences in my prompt, why does bash    wrap lines at the wrong column?E4) If I pipe the output of a command into `read variable', why doesn't    the output show up in $variable when the read command finishes?E5) I have a bunch of shell scripts that use backslash-escaped characters    in arguments to `echo'.  Bash doesn't interpret these characters.  Why    not, and how can I make it understand them?E6) Why doesn't a while or for loop get suspended when I type ^Z?E7) What about empty for loops in Makefiles?E8) Why does the arithmetic evaluation code complain about `08'?E9) Why does the pattern matching expression [A-Z]* match files beginning    with every letter except `z'?E10) Why does `cd //' leave $PWD as `//'?E11) If I resize my xterm while another program is running, why doesn't bash     notice the change?E12) Why don't negative offsets in substring expansion work like I expect?E13) Why does filename completion misbehave if a colon appears in the filename?E14) Why does quoting the pattern argument to the regular expression matching     conditional operator (=~) cause matching to stop working?Section F:  Things to watch out for on certain Unix versionsF1) Why can't I use command line editing in my `cmdtool'?F2) I built bash on Solaris 2.  Why do globbing expansions and filename    completion chop off the first few characters of each filename?F3) Why does bash dump core after I interrupt username completion or    `~user' tilde expansion on a machine running NIS?F4) I'm running SVR4.2.  Why is the line erased every time I type `@'?F5) Why does bash report syntax errors when my C News scripts use a    redirection before a subshell command?F6) Why can't I use vi-mode editing on Red Hat Linux 6.1?F7) Why do bash-2.05a and  bash-2.05b fail to compile `printf.def' on    HP/UX 11.x?Section G:  How can I get bash to do certain common things?G1) How can I get bash to read and display eight-bit characters?G2) How do I write a function `x' to replace builtin command `x', but    still invoke the command from within the function?G3) How can I find the value of a shell variable whose name is the value    of another shell variable?G4) How can I make the bash `time' reserved word print timing output that    looks like the output from my system's /usr/bin/time?G5) How do I get the current directory into my prompt?G6) How can I rename "*.foo" to "*.bar"?G7) How can I translate a filename from uppercase to lowercase?G8) How can I write a filename expansion (globbing) pattern that will match    all files in the current directory except "." and ".."?Section H:  Where do I go from here?H1) How do I report bugs in bash, and where should I look for fixes and    advice?H2) What kind of bash documentation is there?H3) What's coming in future versions?H4) What's on the bash `wish list'?H5) When will the next release appear?----------Section A:  The BasicsA1)  What is it?Bash is a Unix command interpreter (shell).  It is an implementation ofthe Posix 1003.2 shell standard, and resembles the Korn and System Vshells.Bash contains a number of enhancements over those shells, bothfor interactive use and shell programming.  Features gearedtoward interactive use include command line editing, commandhistory, job control, aliases, and prompt expansion.  Programmingfeatures include additional variable expansions, shellarithmetic, and a number of variables and options to controlshell behavior.Bash was originally written by Brian Fox of the Free SoftwareFoundation.  The current developer and maintainer is Chet Rameyof Case Western Reserve University.A2)  What's the latest version?The latest version is 3.2, first made available on 12 October, 2006.A3)  Where can I get it?Bash is the GNU project's shell, and so is available from themaster GNU archive site, ftp.gnu.org, and its mirrors.  Thelatest version is also available for FTP from ftp.cwru.edu.The following URLs tell how to get version 3.2:ftp://ftp.gnu.org/pub/gnu/bash/bash-3.2.tar.gzftp://ftp.cwru.edu/pub/bash/bash-3.2.tar.gzFormatted versions of the documentation are available with the URLs:ftp://ftp.gnu.org/pub/gnu/bash/bash-doc-3.2.tar.gzftp://ftp.cwru.edu/pub/bash/bash-doc-3.2.tar.gzAny patches for the current version are available with the URL:ftp://ftp.cwru.edu/pub/bash/bash-3.2-patches/A4)  On what machines will bash run?Bash has been ported to nearly every version of Unix.  All youshould have to do to build it on a machine for which a portexists is to type `configure' and then `make'.  The build processwill attempt to discover the version of Unix you have and tailoritself accordingly, using a script created by GNU autoconf.More information appears in the file `INSTALL' in the distribution.The Bash web page (http://cnswww.cns.cwru.edu/~chet/bash/bashtop.html)explains how to obtain binary versions of bash for most of the majorcommercial Unix systems.A5) Will bash run on operating systems other than Unix?Configuration specifics for Unix-like systems such as QNX andLynxOS are included in the distribution.  Bash-2.05 and laterversions should compile and run on Minix 2.0 (patches werecontributed), but I don't believe anyone has built bash-2.x onearlier Minix versions yet. Bash has been ported to versions of Windows implementing the Win32programming interface.  This includes Windows 95 and Windows NT.The port was done by Cygnus Solutions (now part of Red Hat) as partof their CYGWIN project.  For more information about the project, seehttp://www.cygwin.com/.Cygnus originally ported bash-1.14.7, and that port was part of theirearly GNU-Win32 (the original name) releases.  Cygnus has also doneports of bash-2.05b and bash-3.0 to the CYGWIN environment, and bothare available as part of their current release.  Bash-3.2 is currentlybeing tested and should be available soon.Bash-2.05b and later versions should require no local Cygnus changes tobuild and run under CYGWIN.DJ Delorie has a port of bash-2.x which runs under MS-DOS, as partof the DJGPP project.  For more information on the project, seehttp://www.delorie.com/djgpp/I have been told that the original DJGPP port was done by Daisuke Aoyama.Mark Elbrecht <snowball3@bigfoot.com> has sent me notice that bash-2.04is available for DJGPP V2.  The files are available as:ftp://ftp.simtel.net/pub/simtelnet/gnu/djgpp/v2gnu/binaryftp://ftp.simtel.net/pub/simtelnet/gnu/djgpp/v2gnu/documentationftp://ftp.simtel.net/pub/simtelnet/gnu/djgpp/v2gnu/sourceMark began to work with bash-2.05, but I don't know the current status.Bash-3.0 compiles and runs with no modifications under Microsoft's Servicesfor Unix (SFU), once known as Interix.  I do not anticipate any problemswith building bash-3.1 or bash-3.2.A6) How can I build bash with gcc? Bash configures to use gcc by default if it is available.  Read thefile INSTALL in the distribution for more information.A7)  How can I make bash my login shell?Some machines let you use `chsh' to change your login shell.  Othersystems use `passwd -s' or `passwd -e'.  If one of these works foryou, that's all you need.  Note that many systems require the fullpathname to a shell to appear in /etc/shells before you can make ityour login shell.  For this, you may need the assistance of yourfriendly local system administrator. If you cannot do this, you can still use bash as your login shell, butyou need to perform some tricks.  The basic idea is to add a commandto your login shell's startup file to replace your login shell withbash.For example, if your login shell is csh or tcsh, and you have installedbash in /usr/gnu/bin/bash, add the following line to ~/.login:if ( -f /usr/gnu/bin/bash ) exec /usr/gnu/bin/bash --login(the `--login' tells bash that it is a login shell).It's not a good idea to put this command into ~/.cshrc, because everycsh you run without the `-f' option, even ones started to run csh scripts,reads that file.  If you must put the command in ~/.cshrc, use somethinglikeif ( $?prompt ) exec /usr/gnu/bin/bash --loginto ensure that bash is exec'd only when the csh is interactive.If your login shell is sh or ksh, you have to do two things.First, create an empty file in your home directory named `.bash_profile'.The existence of this file will prevent the exec'd bash from trying toread ~/.profile, and re-execing itself over and over again.  ~/.bash_profileis the first file bash tries to read initialization commands from whenit is invoked as a login shell.Next, add a line similar to the above to ~/.profile:[ -f /usr/gnu/bin/bash ] && [ -x /usr/gnu/bin/bash ] && \exec /usr/gnu/bin/bash --loginThis will cause login shells to replace themselves with bash running asa login shell.  Once you have this working, you can copy your initializationcode from ~/.profile to ~/.bash_profile.I have received word that the recipe supplied above is insufficient formachines running CDE.  CDE has a maze of twisty little startup files, allslightly different.If you cannot change your login shell in the password file to bash, youwill have to (apparently) live with CDE using the shell in the passwordfile to run its startup scripts.  If you have changed your shell to bash,there is code in the CDE startup files (on Solaris, at least) that attemptsto do the right thing.  It is, however, often broken, and may require thatyou use the $BASH_ENV trick described below.`dtterm' claims to use $SHELL as the default program to start, so if youcan change $SHELL in the CDE startup files, you should be able to use bashin your terminal windows.Setting DTSOURCEPROFILE in ~/.dtprofile will cause the `Xsession' programto read your login shell's startup files.  You may be able to use bash forthe rest of the CDE programs by setting SHELL to bash in ~/.dtprofile aswell, but I have not tried this.You can use the above `exec' recipe to start bash when not logging in withCDE by testing the value of the DT variable:if [ -n "$DT" ]; then        [ -f /usr/gnu/bin/bash ] && exec /usr/gnu/bin/bash --loginfiIf CDE starts its shells non-interactively during login, the login shellstartup files (~/.profile, ~/.bash_profile) will not be sourced at login.To get around this problem, append a line similar to the following to your~/.dtprofile:BASH_ENV=${HOME}/.bash_profile ; export BASH_ENVand add the following line to the beginning of ~/.bash_profile:unset BASH_ENVA8) I just changed my login shell to bash, and now I can't FTP into my   machine.  Why not?You must add the full pathname to bash to the file /etc/shells.  Asnoted in the answer to the previous question, many systems requirethis before you can make bash your login shell. Most versions of ftpd use this file to prohibit `special' userssuch as `uucp' and `news' from using FTP. A9)  What's the `POSIX Shell and Utilities standard'?POSIX is a name originally coined by Richard Stallman for afamily of open system standards based on UNIX.  There are anumber of aspects of UNIX under consideration forstandardization, from the basic system services at the systemcall and C library level to applications and tools to systemadministration and management.  Each area of standardization isassigned to a working group in the 1003 series. The POSIX Shell and Utilities standard was originally developed byIEEE Working Group 1003.2 (POSIX.2).  Today it has been merged withthe original 1003.1 Working Group and is maintained by the AustinGroup (a joint working group of the IEEE, The Open Group andISO/IEC SC22/WG15).  Today the Shell and Utilities are a volumewithin the set of documents that make up IEEE Std 1003.1-2001, andthus now the former POSIX.2 (from 1992) is now part of the currentPOSIX.1 standard (POSIX 1003.1-2001). The Shell and Utilities volume concentrates on the commandinterpreter interface and utility programs commonly executed fromthe command line or by other programs.  The standard is freelyavailable on the web athttp://www.UNIX-systems.org/version3/ . Work continues at the Austin Group on maintenance issues; seehttp://www.opengroup.org/austin/ to join the discussions. Bash is concerned with the aspects of the shell's behavior definedby the POSIX Shell and Utilities volume.  The shell commandlanguage has of course been standardized, including the basic flowcontrol and program execution constructs, I/O redirection andpipelining, argument handling, variable expansion, and quoting. The `special' builtins, which must be implemented as part of theshell to provide the desired functionality, are specified asbeing part of the shell; examples of these are `eval' and`export'.  Other utilities appear in the sections of POSIX notdevoted to the shell which are commonly (and in some cases mustbe) implemented as builtin commands, such as `read' and `test'. POSIX also specifies aspects of the shell's interactivebehavior as part of the UPE, including job control and commandline editing.  Only vi-style line editing commands have beenstandardized; emacs editing commands were left out due toobjections.The latest version of the POSIX Shell and Utilities standard isavailable (now updated to the 2004 Edition) as part of the SingleUNIX Specification Version 3 athttp://www.UNIX-systems.org/version3/A10)  What is the bash `posix mode'?Although bash is an implementation of the POSIX shellspecification, there are areas where the bash default behaviordiffers from that spec.  The bash `posix mode' changes the bashbehavior in these areas so that it obeys the spec more closely. Posix mode is entered by starting bash with the --posix or'-o posix' option or executing `set -o posix' after bash is running.The specific aspects of bash which change when posix mode isactive are listed in the file POSIX in the bash distribution.They are also listed in a section in the Bash Reference Manual(from which that file is generated).Section B:  The latest versionB1) What's new in version 3.2?Bash-3.2 is the second maintenance release of the third major release ofbash.  It contains the following significant new features (see the manualpage for complete descriptions and the CHANGES and NEWS files in thebash-3.2 distribution).o Bash-3.2 now checks shell scripts for NUL characters rather than non-printing  characters when deciding whether or not a script is a binary file.o Quoting the string argument to the [[ command's  =~ (regexp) operator now  forces string matching, as with the other pattern-matching operators.A short feature history dating from Bash-2.0:Bash-3.1 contained the following new features:o Bash-3.1 may now be configured and built in a mode that enforces strict  POSIX compliance.o The `+=' assignment operator, which appends to the value of a string or  array variable, has been implemented.o It is now possible to ignore case when matching in contexts other than  filename generation using the new `nocasematch' shell option.Bash-3.0 contained the following new features:o Features to support the bash debugger have been implemented, and there  is a new `extdebug' option to turn the non-default options ono HISTCONTROL is now a colon-separated list of options and has been  extended with a new `erasedups' option that will result in only one  copy of a command being kept in the history listo Brace expansion has been extended with a new {x..y} form, producing  sequences of digits or characterso Timestamps are now kept with history entries, with an option to save  and restore them from the history file; there is a new HISTTIMEFORMAT  variable describing how to display the timestamps when listing history  entrieso The `[[' command can now perform extended regular expression (egrep-like)  matching, with matched subexpressions placed in the BASH_REMATCH array  variableo A new `pipefail' option causes a pipeline to return a failure status if  any command in it failso The `jobs', `kill', and `wait' builtins now accept job control notation  in their arguments even if job control is not enabledo The `gettext' package and libintl have been integrated, and the shell  messages may be translated into other languagesBash-2.05b introduced the following new features:o support for multibyte characters has been added to both bash and readlineo the DEBUG trap is now run *before* simple commands, ((...)) commands,  [[...]] conditional commands, and for ((...)) loopso the shell now performs arithmetic in the largest integer size the machine  supports (intmax_t)o there is a new \D{...} prompt expansion; passes the `...' to strftime(3)  and inserts the result into the expanded prompto there is a new `here-string' redirection operator:  <<< wordo when displaying variables, function attributes and definitions are shown  separately, allowing them to be re-used as input (attempting to re-use  the old output would result in syntax errors).o `read' has a new `-u fd' option to read from a specified file descriptoro the bash debugger in examples/bashdb has been modified to work with the  new DEBUG trap semantics, the command set has been made more gdb-like,  and the changes to $LINENO make debugging functions work bettero the expansion of $LINENO inside a shell function is only relative to the  function start if the shell is interactive -- if the shell is running a  script, $LINENO expands to the line number in the script.  This is as  POSIX-2001 requiresBash-2.05a introduced the following new features:o The `printf' builtin has undergone major worko There is a new read-only `shopt' option: login_shell, which is set by  login shells and unset otherwiseo New `\A' prompt string escape sequence; expanding to time in 24-hour  HH:MM formato New `-A group/-g' option to complete and compgen; goes group name  completiono New [+-]O invocation option to set and unset `shopt' options at startupo ksh-like `ERR' trapo `for' loops now allow empty word lists after the `in' reserved wordo new `hard' and `soft' arguments for the `ulimit' builtino Readline can be configured to place the user at the same point on the line  when retrieving commands from the history listo Readline can be configured to skip `hidden' files (filenames with a leading  `.' on Unix) when performing completionBash-2.05 introduced the following new features:o This version has once again reverted to using locales and strcoll(3) when  processing pattern matching bracket expressions, as POSIX requires. o Added a new `--init-file' invocation argument as a synonym for `--rcfile',  per the new GNU coding standards.o The /dev/tcp and /dev/udp redirections now accept service names as well as  port numbers.o `complete' and `compgen' now take a `-o value' option, which controls some   of the aspects of that compspec.  Valid values are:        default - perform bash default completion if programmable                  completion produces no matches        dirnames - perform directory name completion if programmable                   completion produces no matches        filenames - tell readline that the compspec produces filenames,                    so it can do things like append slashes to                    directory names and suppress trailing spaceso A new loadable builtin, realpath, which canonicalizes and expands symlinks  in pathname arguments.o When `set' is called without options, it prints function defintions in a  way that allows them to be reused as input.  This affects `declare' and   `declare -p' as well.  This only happens when the shell is not in POSIX   mode, since POSIX.2 forbids this behavior.Bash-2.04 introduced the following new features:o Programmable word completion with the new `complete' and `compgen' builtins;  examples are provided in examples/complete/complete-exampleso `history' has a new `-d' option to delete a history entryo `bind' has a new `-x' option to bind key sequences to shell commandso The prompt expansion code has new `\j' and `\l' escape sequenceso The `no_empty_cmd_completion' shell option, if enabled, inhibits  command completion when TAB is typed on an empty lineo `help' has a new `-s' option to print a usage synopsiso New arithmetic operators: var++, var--, ++var, --var, expr1,expr2 (comma)o New ksh93-style arithmetic for command:for ((expr1 ; expr2; expr3 )); do list; doneo `read' has new options: `-t', `-n', `-d', `-s'o The redirection code handles several filenames specially:  /dev/fd/N,  /dev/stdin, /dev/stdout, /dev/stderro The redirection code now recognizes /dev/tcp/HOST/PORT and  /dev/udp/HOST/PORT and tries to open a TCP or UDP socket, respectively,  to the specified port on the specified hosto The ${!prefix*} expansion has been implementedo A new FUNCNAME variable, which expands to the name of a currently-executing  functiono The GROUPS variable is no longer readonlyo A new shopt `xpg_echo' variable, to control the behavior of echo with  respect to backslash-escape sequences at runtimeo The NON_INTERACTIVE_LOGIN_SHELLS #define has returnedThe version of Readline released with Bash-2.04, Readline-4.1, had severalnew features as well:o Parentheses matching is always compiled into readline, and controllable  with the new `blink-matching-paren' variableo The history-search-forward and history-search-backward functions now leave  point at the end of the line when the search string is empty, like  reverse-search-history, and forward-search-historyo A new function for applications:  rl_on_new_line_with_prompt()o New variables for applications:  rl_already_prompted, and rl_gnu_readline_pBash-2.03 had very few new features, in keeping with the conventionthat odd-numbered releases provide mainly bug fixes.  A number of newfeatures were added to Readline, mostly at the request of the Cygnusfolks.A new shopt option, `restricted_shell', so that startup files can testwhether or not the shell was started in restricted modeFilename generation is now performed on the words between ( and ) incompound array assignments (this is really a bug fix)OLDPWD is now auto-exported, as POSIX.2 requiresENV and BASH_ENV are read-only variables in a restricted shellBash may now be linked against an already-installed Readline library,as long as the Readline library is version 4 or newerAll shells begun with the `--login' option will source the login shellstartup files, even if the shell is not interactiveThere were lots of changes to the version of the Readline library releasedalong with Bash-2.03.  For a complete list of the changes, read the fileCHANGES in the Bash-2.03 distribution.Bash-2.02 contained the following new features:a new version of malloc (based on the old GNU malloc code in previousbash versions) that is more page-oriented, more conservativewith memory usage, does not `orphan' large blocks when theyare freed, is usable on 64-bit machines, and has allocationchecking turned on unconditionallyPOSIX.2-style globbing character classes ([:alpha:], [:alnum:], etc.)POSIX.2-style globbing equivalence classesPOSIX.2-style globbing collating symbolsthe ksh [[...]] extended conditional commandthe ksh egrep-style extended pattern matching operatorsa new `printf' builtinthe ksh-like $(<filename) command substitution, which is equivalent to$(cat filename)new tilde prefixes that expand to directories from the directory stacknew `**' arithmetic operator to do exponentiationcase-insensitive globbing (filename expansion)menu completion a la tcsh`magic-space' history expansion function like tcshthe readline inputrc `language' has a new file inclusion directive ($include)Bash-2.01 contained only a few new features:new `GROUPS' builtin array variable containing the user's group listnew bindable readline commands: history-and-alias-expand-line andalias-expand-lineBash-2.0 contained extensive changes and new features from bash-1.14.7.Here's a short list:new `time' reserved word to time pipelines, shell builtins, andshell functionsone-dimensional arrays with a new compound assignment statement,        appropriate expansion constructs and modifications to someof the builtins (read, declare, etc.) to use themnew quoting syntaxes for ANSI-C string expansion and locale-specificstring translationnew expansions to do substring extraction, pattern replacement, andindirect variable expansionnew builtins: `disown' and `shopt'new variables: HISTIGNORE, SHELLOPTS, PIPESTATUS, DIRSTACK, GLOBIGNORE,       MACHTYPE, BASH_VERSINFOspecial handling of many unused or redundant variables removed(e.g., $notify, $glob_dot_filenames, $no_exit_on_failed_exec)dynamic loading of new builtin commands; many loadable examples providednew prompt expansions: \a, \e, \n, \H, \T, \@, \v, \Vhistory and aliases available in shell scriptsnew readline variables: enable-keypad, mark-directories, input-meta,visible-stats, disable-completion, comment-beginnew readline commands to manipulate the mark and operate on the regionnew readline emacs mode commands and bindings for ksh-88 compatibilityupdated and extended builtinsnew DEBUG trapexpanded (and now documented) restricted shell modeimplementation stuff:autoconf-based configurationnearly all of the bugs reported since version 1.14 have been fixedmost builtins converted to use builtin `getopt' for consistencymost builtins use -p option to display output in a reusable form(for consistency)grammar tighter and smaller (66 reduce-reduce conflicts gone)lots of code now smaller and fastertest suite greatly expandedB2) Are there any user-visible incompatibilities between bash-3.2 and    bash-2.05b?There are a few incompatibilities between version 2.05b and version 3.2.They are detailed in the file COMPAT in the bash distribution.  That fileis not meant to be all-encompassing; send mail tobash-maintainers@gnu.orgif if you find something that's not mentioned there.Section C:  Differences from other Unix shellsC1) How does bash differ from sh, the Bourne shell?This is a non-comprehensive list of features that differentiate bashfrom the SVR4.2 shell.  The bash manual page explains these morecompletely.Things bash has that sh does not:long invocation options[+-]O invocation option-l invocation option`!' reserved word to invert pipeline return value`time' reserved word to time pipelines and shell builtinsthe `function' reserved wordthe `select' compound command and reserved wordarithmetic for command: for ((expr1 ; expr2; expr3 )); do list; donenew $'...' and $"..." quotingthe $(...) form of command substitutionthe $(<filename) form of command substitution, equivalent to$(cat filename)the ${#param} parameter value length operatorthe ${!param} indirect parameter expansion operatorthe ${!param*} prefix expansion operatorthe ${param:offset[:length]} parameter substring operatorthe ${param/pat[/string]} parameter pattern substitution operatorexpansions to perform substring removal (${p%[%]w}, ${p#[#]w})expansion of positional parameters beyond $9 with ${num}variables: BASH, BASH_VERSION, BASH_VERSINFO, UID, EUID, REPLY,   TIMEFORMAT, PPID, PWD, OLDPWD, SHLVL, RANDOM, SECONDS,   LINENO, HISTCMD, HOSTTYPE, OSTYPE, MACHTYPE, HOSTNAME,   ENV, PS3, PS4, DIRSTACK, PIPESTATUS, HISTSIZE, HISTFILE,   HISTFILESIZE, HISTCONTROL, HISTIGNORE, GLOBIGNORE, GROUPS,   PROMPT_COMMAND, FCEDIT, FIGNORE, IGNOREEOF, INPUTRC,   SHELLOPTS, OPTERR, HOSTFILE, TMOUT, FUNCNAME, histchars,   auto_resumeDEBUG trapERR trapvariable arrays with new compound assignment syntaxredirections: <>, &>, >|, <<<, [n]<&word-, [n]>&word-prompt string special char translation and variable expansionauto-export of variables in initial environmentcommand search finds functions before builtinsbash return builtin will exit a file sourced with `.'builtins: cd -/-L/-P, exec -l/-c/-a, echo -e/-E, hash -d/-l/-p/-t.  export -n/-f/-p/name=value, pwd -L/-P,  read -e/-p/-a/-t/-n/-d/-s/-u,  readonly -a/-f/name=value, trap -l, set +o,  set -b/-m/-o option/-h/-p/-B/-C/-H/-P,  unset -f/-v, ulimit -i/-m/-p/-q/-u/-x,  type -a/-p/-t/-f/-P, suspend -f, kill -n,  test -o optname/s1 == s2/s1 < s2/s1 > s2/-nt/-ot/-ef/-O/-G/-Sbash reads ~/.bashrc for interactive shells, $ENV for non-interactivebash restricted shell mode is more extensivebash allows functions and variables with the same namebrace expansiontilde expansionarithmetic expansion with $((...)) and `let' builtinthe `[[...]]' extended conditional commandprocess substitutionaliases and alias/unalias builtinslocal variables in functions and `local' builtinreadline and command-line editing with programmable completioncommand history and history/fc builtinscsh-like history expansionother new bash builtins: bind, command, compgen, complete, builtin, declare/typeset, dirs, enable, fc, help, history, logout, popd, pushd, disown, shopt, printfexported functionsfilename generation when using output redirection (command >a*)POSIX.2-style globbing character classesPOSIX.2-style globbing equivalence classesPOSIX.2-style globbing collating symbolsegrep-like extended pattern matching operatorscase-insensitive pattern matching and globbingvariable assignments preceding commands affect only that command,even for builtins and functionsposix mode and strict posix conformanceredirection to /dev/fd/N, /dev/stdin, /dev/stdout, /dev/stderr,/dev/tcp/host/port, /dev/udp/host/portdebugger support, including `caller' builtin and new variablesRETURN trapthe `+=' assignment operatorThings sh has that bash does not:uses variable SHACCT to do shell accountingincludes `stop' builtin (bash can use alias stop='kill -s STOP')`newgrp' builtinturns on job control if called as `jsh'$TIMEOUT (like bash $TMOUT)`^' is a synonym for `|'new SVR4.2 sh builtins: mldmode, privImplementation differences:redirection to/from compound commands causes sh to create a subshellbash does not allow unbalanced quotes; sh silently inserts them at EOFbash does not mess with signal 11sh sets (euid, egid) to (uid, gid) if -p not supplied and uid < 100bash splits only the results of expansions on IFS, using POSIX.2field splitting rules; sh splits all words on IFSsh does not allow MAILCHECK to be unset (?)sh does not allow traps on SIGALRM or SIGCHLDbash allows multiple option arguments when invoked (e.g. -x -v);sh allows only a single option argument (`sh -x -v' attemptsto open a file named `-v', and, on SunOS 4.1.4, dumps core.On Solaris 2.4 and earlier versions, sh goes into an infiniteloop.)sh exits a script if any builtin fails; bash exits only if one ofthe POSIX.2 `special' builtins failsC2)  How does bash differ from the Korn shell, version ksh88?Things bash has or uses that ksh88 does not:long invocation options[-+]O invocation option-l invocation option`!' reserved wordarithmetic for command: for ((expr1 ; expr2; expr3 )); do list; donearithmetic in largest machine-supported size (intmax_t)posix mode and posix conformancecommand hashingtilde expansion for assignment statements that look like $PATHprocess substitution with named pipes if /dev/fd is not availablethe ${!param} indirect parameter expansion operatorthe ${!param*} prefix expansion operatorthe ${param:offset[:length]} parameter substring operatorthe ${param/pat[/string]} parameter pattern substitution operatorvariables: BASH, BASH_VERSION, BASH_VERSINFO, UID, EUID, SHLVL,   TIMEFORMAT, HISTCMD, HOSTTYPE, OSTYPE, MACHTYPE,   HISTFILESIZE, HISTIGNORE, HISTCONTROL, PROMPT_COMMAND,   IGNOREEOF, FIGNORE, INPUTRC, HOSTFILE, DIRSTACK,   PIPESTATUS, HOSTNAME, OPTERR, SHELLOPTS, GLOBIGNORE,   GROUPS, FUNCNAME, histchars, auto_resumeprompt expansion with backslash escapes and command substitutionredirection: &> (stdout and stderr), <<<, [n]<&word-, [n]>&word-more extensive and extensible editing and programmable completionbuiltins: bind, builtin, command, declare, dirs, echo -e/-E, enable,  exec -l/-c/-a, fc -s, export -n/-f/-p, hash, help, history,  jobs -x/-r/-s, kill -s/-n/-l, local, logout, popd, pushd,  read -e/-p/-a/-t/-n/-d/-s, readonly -a/-n/-f/-p,  set -o braceexpand/-o histexpand/-o interactive-comments/  -o notify/-o physical/-o posix/-o hashall/-o onecmd/  -h/-B/-C/-b/-H/-P, set +o, suspend, trap -l, type,  typeset -a/-F/-p, ulimit -i/-q/-u/-x, umask -S, alias -p,  shopt, disown, printf, complete, compgen`!' csh-style history expansionPOSIX.2-style globbing character classesPOSIX.2-style globbing equivalence classesPOSIX.2-style globbing collating symbolsegrep-like extended pattern matching operatorscase-insensitive pattern matching and globbing`**' arithmetic operator to do exponentiationredirection to /dev/fd/N, /dev/stdin, /dev/stdout, /dev/stderrarrays of unlimited sizeTMOUT is default timeout for `read' and `select'debugger support, including the `caller' builtinRETURN trapTimestamps in history entries{x..y} brace expansionThe `+=' assignment operatorThings ksh88 has or uses that bash does not:tracked aliases (alias -t)variables: ERRNO, FPATH, EDITOR, VISUALco-processes (|&, >&p, <&p)weirdly-scoped functionstypeset +f to list all function names without definitionstext of command history kept in a file, not memorybuiltins: alias -x, cd old new, newgrp, print,  read -p/-s/var?prompt, set -A/-o gmacs/  -o bgnice/-o markdirs/-o trackall/-o viraw/-s,  typeset -H/-L/-R/-Z/-A/-ft/-fu/-fx/-l/-u/-t, whenceusing environment to pass attributes of exported variablesarithmetic evaluation done on arguments to some builtinsreads .profile from $PWD when invoked as login shellImplementation differences:ksh runs last command of a pipeline in parent shell contextbash has brace expansion by default (ksh88 compile-time option)bash has fixed startup file for all interactive shells; ksh reads $ENVbash has exported functionsbash command search finds functions before builtinsbash waits for all commands in pipeline to exit before returning statusemacs-mode editing has some slightly different key bindingsC3)  Which new features in ksh-93 are not in bash, and which are?New things in ksh-93 not in bash-3.2:associative arraysfloating point arithmetic and variablesmath library functions${!name[sub]} name of subscript for associative array`.' is allowed in variable names to create a hierarchical namespacemore extensive compound assignment syntaxdiscipline functions`sleep' and `getconf' builtins (bash has loadable versions)typeset -n and `nameref' variablesKEYBD trapvariables: .sh.edchar, .sh.edmode, .sh.edcol, .sh.edtext, .sh.version,   .sh.name, .sh.subscript, .sh.value, .sh.match, HISTEDITbackreferences in pattern matching (\N)`&' operator in pattern lists for matchingprint -f (bash uses printf)`fc' has been renamed to `hist'`.' can execute shell functionsexit statuses between 0 and 255FPATH and PATH mixinggetopts -a-I invocation optionprintf %H, %P, %T, %Z modifiers, output base for %dlexical scoping for local variables in `ksh' functionsno scoping for local variables in `POSIX' functionsNew things in ksh-93 present in bash-3.2:[n]<&word- and [n]>&word- redirections (combination dup and close)        for (( expr1; expr2; expr3 )) ; do list; done - arithmetic for command        ?:, ++, --, `expr1 , expr2' arithmetic operatorsexpansions: ${!param}, ${param:offset[:len]}, ${param/pat[/str]},    ${!param*}compound array assignmentthe `!' reserved wordloadable builtins -- but ksh uses `builtin' while bash uses `enable'`command', `builtin', `disown' builtinsnew $'...' and $"..." quotingFIGNORE (but bash uses GLOBIGNORE), HISTCMDset -o notify/-Cchanges to kill builtinread -A (bash uses read -a)        read -t/-dtrap -pexec -c/-a`.' restores the positional parameters when it completesPOSIX.2 `test'umask -Sunalias -acommand and arithmetic substitution performed on PS1, PS4, and ENVcommand name completionENV processed only for interactive shellsset -o pipefailThe `+=' assignment operatorSection D:  Why does bash do some things differently than other Unix shells?D1) Why does bash run a different version of `command' than    `which command' says it will?On many systems, `which' is actually a csh script that assumesyou're running csh.  In tcsh, `which' and its cousin `where'are builtins.  On other Unix systems, `which' is a perl scriptthat uses the PATH environment variable.  Many Linux distributionsuse GNU `which', which is a C program that can understand shellaliases.The csh script version reads the csh startup files from yourhome directory and uses those to determine which `command' willbe invoked.  Since bash doesn't use any of those startup files,there's a good chance that your bash environment differs fromyour csh environment.  The bash `type' builtin does everything`which' does, and will report correct results for the runningshell.  If you're really wedded to the name `which', try addingthe following function definition to your .bashrc:which(){builtin type "$@"}If you're moving from tcsh and would like to bring `where' alongas well, use this function:where(){builtin type -a "$@"}D2) Why doesn't bash treat brace expansions exactly like csh?The only difference between bash and csh brace expansion is thatbash requires a brace expression to contain at least one unquotedcomma if it is to be expanded.  Any brace-surrounded word notcontaining an unquoted comma is left unchanged by the braceexpansion code.  This affords the greatest degree of shcompatibility. Bash, ksh, zsh, and pd-ksh all implement brace expansion this way. D3) Why doesn't bash have csh variable modifiers?Posix has specified a more powerful, albeit somewhat more cryptic,mechanism cribbed from ksh, and bash implements it.${parameter%word}        Remove smallest suffix pattern.  The WORD is expanded to produce        a pattern.  It then expands to the value of PARAMETER, with the        smallest portion of the suffix matched by the pattern deleted.        x=file.c        echo ${x%.c}.o        -->file.o${parameter%%word}        Remove largest suffix pattern.  The WORD is expanded to produce        a pattern.  It then expands to the value of PARAMETER, with the        largest portion of the suffix matched by the pattern deleted.        x=posix/src/std        echo ${x%%/*}        -->posix${parameter#word}        Remove smallest prefix pattern.  The WORD is expanded to produce        a pattern.  It then expands to the value of PARAMETER, with the        smallest portion of the prefix matched by the pattern deleted.        x=$HOME/src/cmd        echo ${x#$HOME}        -->/src/cmd${parameter##word}        Remove largest prefix pattern.  The WORD is expanded to produce        a pattern.  It then expands to the value of PARAMETER, with the        largest portion of the prefix matched by the pattern deleted.        x=/one/two/three        echo ${x##*/}        -->threeGivena=/a/b/c/db=b.xxxcshbashresult-------------$a:h${a%/*}   /a/b/c$a:t${a##*/}   d$b:r${b%.*}   b$b:e${b##*.}   xxxD4) How can I make my csh aliases work when I convert to bash?Bash uses a different syntax to support aliases than csh does. The details can be found in the documentation.  We have provideda shell script which does most of the work of conversion for you;this script can be found in ./examples/misc/aliasconv.sh.  Here ishow you use it:  Start csh in the normal way for you.  (e.g., `csh')  Pipe the output of `alias' through `aliasconv.sh', saving theresults into `bash_aliases':  alias | bash aliasconv.sh >bash_aliases  Edit `bash_aliases', carefully reading through any createdfunctions.  You will need to change the names of some csh specificvariables to the bash equivalents.  The script converts $cwd to$PWD, $term to $TERM, $home to $HOME, $user to $USER, and $promptto $PS1.  You may also have to add quotes to avoid unwantedexpansion.For example, the csh alias:  alias cd 'cd \!*; echo $cwd'  is converted to the bash function:cd () { command cd "$@"; echo $PWD ; }The only thing that needs to be done is to quote $PWD:  cd () { command cd "$@"; echo "$PWD" ; }  Merge the edited file into your ~/.bashrc.There is an additional, more ambitious, script inexamples/misc/cshtobash that attempts to convert your entire cshenvironment to its bash equivalent.  This script can be run assimply `cshtobash' to convert your normal interactiveenvironment, or as `cshtobash ~/.login' to convert your loginenvironment. D5) How can I pipe standard output and standard error from one command to    another, like csh does with `|&'?Usecommand 2>&1 | command2The key is to remember that piping is performed before redirection, sofile descriptor 1 points to the pipe when it is duplicated onto filedescriptor 2.D6) Now that I've converted from ksh to bash, are there equivalents to    ksh features like autoloaded functions and the `whence' command?There are features in ksh-88 and ksh-93 that do not have direct bashequivalents.  Most, however, can be emulated with very little trouble.ksh-88 featureBash equivalent-----------------------------compiled-in aliasesset up aliases in .bashrc; some ksh aliases arebash builtins (hash, history, type)coprocessesnamed pipe pairs (one for read, one for write)typeset +fdeclare -Fcd, print, whencefunction substitutes in examples/functions/kshenvautoloaded functionsexamples/functions/autoload is the same as typeset -furead var?promptread -p prompt varksh-93 featureBash equivalent-----------------------------sleep, getconfBash has loadable versions in examples/loadables${.sh.version}$BASH_VERSIONprint -fprintfhistalias hist=fc$HISTEDIT$FCEDITSection E:  How can I get bash to do certain things, and why does bash do    things the way it does?E1) Why is the bash builtin `test' slightly different from /bin/test?The specific example used here is [ ! x -o x ], which is false.Bash's builtin `test' implements the Posix.2 spec, which can besummarized as follows (the wording is due to David Korn):   Here is the set of rules for processing test arguments.      0 Args: False    1 Arg:  True iff argument is not null.    2 Args: If first arg is !, True iff second argument is null.    If first argument is unary, then true if unary test is true    Otherwise error.    3 Args: If second argument is a binary operator, do binary test of $1 $3    If first argument is !, negate two argument test of $2 $3    If first argument is `(' and third argument is `)', do the    one-argument test of the second argument.    Otherwise error.    4 Args: If first argument is !, negate three argument test of $2 $3 $4.    Otherwise unspecified    5 or more Args: unspecified.  (Historical shells would use their    current algorithm).   The operators -a and -o are considered binary operators for the purposeof the 3 Arg case.   As you can see, the test becomes (not (x or x)), which is false.E2) Why does bash sometimes say `Broken pipe'?If a sequence of commands appears in a pipeline, and one of thereading commands finishes before the writer has finished, thewriter receives a SIGPIPE signal.  Many other shells special-caseSIGPIPE as an exit status in the pipeline and do not report it. For example, in:        ps -aux | head  `head' can finish before `ps' writes all of its output, and pswill try to write on a pipe without a reader.  In that case, bashwill print `Broken pipe' to stderr when ps is killed by aSIGPIPE. As of bash-3.1, bash does not report SIGPIPE errors by default.  Youcan build a version of bash that will report such errors.E3) When I have terminal escape sequences in my prompt, why does bash    wrap lines at the wrong column?Readline, the line editing library that bash uses, does not knowthat the terminal escape sequences do not take up space on thescreen.  The redisplay code assumes, unless told otherwise, thateach character in the prompt is a `printable' character thattakes up one character position on the screen. You can use the bash prompt expansion facility (see the PROMPTINGsection in the manual page) to tell readline that sequences ofcharacters in the prompt strings take up no screen space. Use the \[ escape to begin a sequence of non-printing characters,and the \] escape to signal the end of such a sequence. E4) If I pipe the output of a command into `read variable', why doesn't    the output show up in $variable when the read command finishes?This has to do with the parent-child relationship between Unixprocesses.  It affects all commands run in pipelines, not justsimple calls to `read'.  For example, piping a command's outputinto a `while' loop that repeatedly calls `read' will result inthe same behavior.Each element of a pipeline, even a builtin or shell function,runs in a separate process, a child of the shell running thepipeline.  A subprocess cannot affect its parent's environment. When the `read' command sets the variable to the input, thatvariable is set only in the subshell, not the parent shell.  Whenthe subshell exits, the value of the variable is lost. Many pipelines that end with `read variable' can be convertedinto command substitutions, which will capture the output ofa specified command.  The output can then be assigned to avariable:grep ^gnu /usr/lib/news/active | wc -l | read ngroupcan be converted intongroup=$(grep ^gnu /usr/lib/news/active | wc -l)This does not, unfortunately, work to split the text amongmultiple variables, as read does when given multiple variablearguments.  If you need to do this, you can either use thecommand substitution above to read the output into a variableand chop up the variable using the bash pattern removalexpansion operators or use some variant of the followingapproach.Say /usr/local/bin/ipaddr is the following shell script:#! /bin/shhost `hostname` | awk '/address/ {print $NF}'Instead of using/usr/local/bin/ipaddr | read A B C Dto break the local machine's IP address into separate octets, useOIFS="$IFS"IFS=.set -- $(/usr/local/bin/ipaddr)IFS="$OIFS"A="$1" B="$2" C="$3" D="$4"Beware, however, that this will change the shell's positionalparameters.  If you need them, you should save them before doingthis.This is the general approach -- in most cases you will not need toset $IFS to a different value.Some other user-supplied alternatives include:read A B C D << HERE    $(IFS=.; echo $(/usr/local/bin/ipaddr))HEREand, where process substitution is available,read A B C D < <(IFS=.; echo $(/usr/local/bin/ipaddr))E5) I have a bunch of shell scripts that use backslash-escaped characters    in arguments to `echo'.  Bash doesn't interpret these characters.  Why    not, and how can I make it understand them?This is the behavior of echo on most Unix System V machines.The bash builtin `echo' is modeled after the 9th EditionResearch Unix version of `echo'.  It does not interpretbackslash-escaped characters in its argument strings by default;it requires the use of the -e option to enable theinterpretation.  The System V echo provides no way to disable thespecial characters; the bash echo has a -E option to disablethem. There is a configuration option that will make bash behave likethe System V echo and interpret things like `\t' by default.  Runconfigure with the --enable-xpg-echo-default option to turn thison.  Be aware that this will cause some of the tests run when youtype `make tests' to fail.There is a shell option, `xpg_echo', settable with `shopt', that willchange the behavior of echo at runtime.  Enabling this option turnson expansion of backslash-escape sequences.E6) Why doesn't a while or for loop get suspended when I type ^Z?This is a consequence of how job control works on Unix.  The onlything that can be suspended is the process group.  This is a singlecommand or pipeline of commands that the shell forks and executes.When you run a while or for loop, the only thing that the shell forksand executes are any commands in the while loop test and commands inthe loop bodies.  These, therefore, are the only things that can besuspended when you type ^Z.If you want to be able to stop the entire loop, you need to put itwithin parentheses, which will force the loop into a subshell thatmay be stopped (and subsequently restarted) as a single unit.E7) What about empty for loops in Makefiles?It's fairly common to see constructs like this in automatically-generatedMakefiles:SUBDIRS = @SUBDIRS@...subdirs-clean:for d in ${SUBDIRS}; do \( cd $$d && ${MAKE} ${MFLAGS} clean ) \doneWhen SUBDIRS is empty, this results in a command like this being passed tobash:for d in ; do( cd $d && ${MAKE} ${MFLAGS} clean )doneIn versions of bash before bash-2.05a, this was a syntax error.  If thereserved word `in' was present, a word must follow it before the semicolonor newline.  The language in the manual page referring to the list of wordsbeing empty referred to the list after it is expanded.  These versions ofbash required that there be at least one word following the `in' when theconstruct was parsed.The idiomatic Makefile solution is something like:SUBDIRS = @SUBDIRS@subdirs-clean:subdirs=$SUBDIRS ; for d in $$subdirs; do \( cd $$d && ${MAKE} ${MFLAGS} clean ) \doneThe latest updated POSIX standard has changed this:  the word listis no longer required.  Bash versions 2.05a and later accept thenew syntax.E8) Why does the arithmetic evaluation code complain about `08'?The bash arithmetic evaluation code (used for `let', $(()), (()), and inother places), interprets a leading `0' in numeric constants as denotingan octal number, and a leading `0x' as denoting hexadecimal.  This isin accordance with the POSIX.2 spec, section 2.9.2.1, which states thatarithmetic constants should be handled as signed long integers as definedby the ANSI/ISO C standard.The POSIX.2 interpretation committee has confirmed this:http://www.pasc.org/interps/unofficial/db/p1003.2/pasc-1003.2-173.htmlE9) Why does the pattern matching expression [A-Z]* match files beginning    with every letter except `z'?Bash-2.03, Bash-2.05 and later versions honor the current locale settingwhen processing ranges within pattern matching bracket expressions ([A-Z]). This is what POSIX.2 and SUSv3/XPG6 specify. The behavior of the matcher in bash-2.05 and later versions depends on thecurrent LC_COLLATE setting.  Setting this variable to `C' or `POSIX' willresult in the traditional behavior ([A-Z] matches all uppercase ASCIIcharacters).  Many other locales, including the en_US locale (the defaulton many US versions of Linux) collate the upper and lower case letters likethis:AaBb...Zzwhich means that [A-Z] matches every letter except `z'.  Others collate likeaAbBcC...zZwhich means that [A-Z] matches every letter except `a'.The portable way to specify upper case letters is [:upper:] instead ofA-Z; lower case may be specified as [:lower:] instead of a-z.Look at the manual pages for setlocale(3), strcoll(3), and, if it ispresent, locale(1).  If you have locale(1), you can use it to findyour current locale information even if you do not have any of theLC_ variables set.My advice is to putexport LC_COLLATE=Cinto /etc/profile and inspect any shell scripts run from cron forconstructs like [A-Z].  This will prevent things likerm [A-Z]*from removing every file in the current directory except those beginningwith `z' and still allow individual users to change the collation order.Users may put the above command into their own profiles as well, of course.E10) Why does `cd //' leave $PWD as `//'?POSIX.2, in its description of `cd', says that *three* or more leadingslashes may be replaced with a single slash when canonicalizing thecurrent working directory.This is, I presume, for historical compatibility.  Certain versions ofUnix, and early network file systems, used paths of the form//hostname/path to access `path' on server `hostname'.E11) If I resize my xterm while another program is running, why doesn't bash     notice the change?This is another issue that deals with job control.The kernel maintains a notion of a current terminal process group.  Membersof this process group (processes whose process group ID is equal to thecurrent terminal process group ID) receive terminal-generated signals likeSIGWINCH.  (For more details, see the JOB CONTROL section of the bashman page.)If a terminal is resized, the kernel sends SIGWINCH to each member ofthe terminal's current process group (the `foreground' process group).When bash is running with job control enabled, each pipeline (which may bea single command) is run in its own process group, different from bash'sprocess group.  This foreground process group receives the SIGWINCH; bashdoes not.  Bash has no way of knowing that the terminal has been resized.There is a `checkwinsize' option, settable with the `shopt' builtin, thatwill cause bash to check the window size and adjust its idea of theterminal's dimensions each time a process stops or exits and returns controlof the terminal to bash.  Enable it with `shopt -s checkwinsize'.E12) Why don't negative offsets in substring expansion work like I expect?When substring expansion of the form ${param:offset[:length} is used,an `offset' that evaluates to a number less than zero counts back fromthe end of the expanded value of $param.When a negative `offset' begins with a minus sign, however, unexpected thingscan happen.  Considera=12345678echo ${a:-4}intending to print the last four characters of $a.  The problem is that${param:-word} already has a well-defined meaning: expand to word if theexpanded value of param is unset or null, and $param otherwise.To use negative offsets that begin with a minus sign, separate theminus sign and the colon with a space.E13) Why does filename completion misbehave if a colon appears in the filename?Filename completion (and word completion in general) may appear to behaveimproperly if there is a colon in the word to be completed.The colon is special to readline's word completion code:  it is one of thecharacters that breaks words for the completer.  Readline uses these charactersin sort of the same way that bash uses $IFS: they break or separate the wordsthe completion code hands to the application-specific or default wordcompletion functions.  The original intent was to make it easy to editcolon-separated lists (such as $PATH in bash) in various applications usingreadline for input.This is complicated by the fact that some versions of the popular`bash-completion' programmable completion package have problems with thedefault completion behavior in the presence of colons.  The current set of completion word break characters is available in bash asthe value of the COMP_WORDBREAKS variable.  Removing `:' from that value isenough to make the colon not special to completion:COMP_WORDBREAKS=${COMP_WORDBREAKS//:}You can also quote the colon with a backslash to achieve the same resulttemporarily.E14) Why does quoting the pattern argument to the regular expression matching     conditional operator (=~) cause regexp matching to stop working?In versions of bash prior to bash-3.2, the effect of quoting the regularexpression argument to the [[ command's =~ operator was not specified.The practical effect was that double-quoting the pattern argument requiredbackslashes to quote special pattern characters, which interfered with thebackslash processing performed by double-quoted word expansion and wasinconsistent with how the == shell pattern matching operator treatedquoted characters.In bash-3.2, the shell was changed to internally quote characters in single-and double-quoted string arguments to the =~ operator, which suppresses thespecial meaning of the characters special to regular expression processing(`.', `[', `\', `(', `), `*', `+', `?', `{', `|', `^', and `$') and forcesthem to be matched literally.  This is consistent with how the `==' patternmatching operator treats quoted portions of its pattern argument.Since the treatment of quoted string arguments was changed, several issueshave arisen, chief among them the problem of white space in pattern argumentsand the differing treatment of quoted strings between bash-3.1 and bash-3.2.Both problems may be solved by using a shell variable to hold the pattern.Since word splitting is not performed when expanding shell variables in alloperands of the [[ command, this allows users to quote patterns as they wishwhen assigning the variable, then expand the values to a single string thatmay contain whitespace.  The first problem may be solved by using backslashesor any other quoting mechanism to escape the white space in the patterns.Section F:  Things to watch out for on certain Unix versionsF1) Why can't I use command line editing in my `cmdtool'?The problem is `cmdtool' and bash fighting over the input.  Whenscrolling is enabled in a cmdtool window, cmdtool puts the tty in`raw mode' to permit command-line editing using the mouse forapplications that cannot do it themselves.  As a result, bash andcmdtool each try to read keyboard input immediately, with neithergetting enough of it to be useful.This mode also causes cmdtool to not implement many of theterminal functions and control sequences appearing in the`sun-cmd' termcap entry.  For a more complete explanation, seethat file examples/suncmd.termcap in the bash distribution. `xterm' is a better choice, and gets along with bash much moresmoothly.If you must use cmdtool, you can use the termcap description inexamples/suncmd.termcap.  Set the TERMCAP variable to the terminaldescription contained in that file, i.e.TERMCAP='Mu|sun-cmd:am:bs:km:pt:li#34:co#80:cl=^L:ce=\E[K:cd=\E[J:rs=\E[s:'Then export TERMCAP and start a new cmdtool window from that shell.The bash command-line editing should behave better in the newcmdtool.  If this works, you can put the assignment to TERMCAPin your bashrc file.F2) I built bash on Solaris 2.  Why do globbing expansions and filename    completion chop off the first few characters of each filename?This is the consequence of building bash on SunOS 5 and linkingwith the libraries in /usr/ucblib, but using the definitionsand structures from files in /usr/include. The actual conflict is between the dirent structure in/usr/include/dirent.h and the struct returned by the version of`readdir' in libucb.a (a 4.3-BSD style `struct direct'). Make sure you've got /usr/ccs/bin ahead of /usr/ucb in your $PATHwhen configuring and building bash.  This will ensure that youuse /usr/ccs/bin/cc or acc instead of /usr/ucb/cc and that youlink with libc before libucb. If you have installed the Sun C compiler, you may also need toput /usr/ccs/bin and /opt/SUNWspro/bin into your $PATH before/usr/ucb.F3) Why does bash dump core after I interrupt username completion or    `~user' tilde expansion on a machine running NIS?This is a famous and long-standing bug in the SunOS YP (sorry, NIS)client library, which is part of libc.The YP library code keeps static state -- a pointer into the datareturned from the server.  When YP initializes itself (setpwent),it looks at this pointer and calls free on it if it's non-null. So far, so good. If one of the YP functions is interrupted during getpwent (theexact function is interpretwithsave()), and returns NULL, thepointer is freed without being reset to NULL, and the functionreturns.  The next time getpwent is called, it sees that thispointer is non-null, calls free, and the bash free() blows upbecause it's being asked to free freed memory. The traditional Unix mallocs allow memory to be freed multipletimes; that's probably why this has never been fixed.  You canrun configure with the `--without-gnu-malloc' option to usethe C library malloc and avoid the problem.F4) I'm running SVR4.2.  Why is the line erased every time I type `@'?The `@' character is the default `line kill' character in mostversions of System V, including SVR4.2.  You can change thischaracter to whatever you want using `stty'.  For example, tochange the line kill character to control-u, typestty kill ^Uwhere the `^' and `U' can be two separate characters.F5) Why does bash report syntax errors when my C News scripts use a    redirection before a subshell command?The actual command in question is something like< file ( command )According to the grammar given in the POSIX.2 standard, this constructis, in fact, a syntax error.  Redirections may only precede `simplecommands'.  A subshell construct such as the above is one of the shell's`compound commands'.  A redirection may only follow a compound command.This affects the mechanical transformation of commands that use `cat'to pipe a file into a command (a favorite Useless-Use-Of-Cat topic oncomp.unix.shell).  While most commands of the formcat file | commandcan be converted to `< file command', shell control structures such asloops and subshells require `command < file'.The file CWRU/sh-redir-hack in the bash distribution is an(unofficial) patch to parse.y that will modify the grammar tosupport this construct.  It will not apply with `patch'; you mustmodify parse.y by hand.  Note that if you apply this, you mustrecompile with -DREDIRECTION_HACK.  This introduces a largenumber of reduce/reduce conflicts into the shell grammar. F6) Why can't I use vi-mode editing on Red Hat Linux 6.1?The short answer is that Red Hat screwed up.The long answer is that they shipped an /etc/inputrc that only worksfor emacs mode editing, and then screwed all the vi users by settingINPUTRC to /etc/inputrc in /etc/profile.The short fix is to do one of the following: remove or rename/etc/inputrc, set INPUTRC=~/.inputrc in ~/.bashrc (or .bash_profile,but make sure you export it if you do), remove the assignment toINPUTRC from /etc/profile, add        set keymap emacsto the beginning of /etc/inputrc, or bracket the key bindings in/etc/inputrc with these lines$if mode=emacs[...]$endifF7) Why do bash-2.05a and bash-2.05b fail to compile `printf.def' on    HP/UX 11.x?HP/UX's support for long double is imperfect at best.GCC will support it without problems, but the HP C library functionslike strtold(3) and printf(3) don't actually work with long doubles.HP implemented a `long_double' type as a 4-element array of 32-bitints, and that is what the library functions use.  The ANSI C`long double' type is a 128-bit floating point scalar.The easiest fix, until HP fixes things up, is to edit the generatedconfig.h and #undef the HAVE_LONG_DOUBLE line.  After doing that,the compilation should complete successfully.Section G:  How can I get bash to do certain common things?G1) How can I get bash to read and display eight-bit characters?This is a process requiring several steps.First, you must ensure that the `physical' data path is a full eightbits.  For xterms, for example, the `vt100' resources `eightBitInput'and `eightBitOutput' should be set to `true'.Once you have set up an eight-bit path, you must tell the kernel andtty driver to leave the eighth bit of characters alone when processingkeyboard input.  Use `stty' to do this:stty cs8 -istrip -parenbFor old BSD-style systems, you can usestty pass8You may also needstty even oddFinally, you need to tell readline that you will be inputting anddisplaying eight-bit characters.  You use readline variables to dothis.  These variables can be set in your .inputrc or using the bash`bind' builtin.  Here's an example using `bind':bash$ bind 'set convert-meta off'bash$ bind 'set meta-flag on'bash$ bind 'set output-meta on'The `set' commands between the single quotes may also be placedin ~/.inputrc.The script examples/scripts.noah/meta.bash encapsulates the bindcommands in a shell function.G2) How do I write a function `x' to replace builtin command `x', but    still invoke the command from within the function?This is why the `command' and `builtin' builtins exist.  The`command' builtin executes the command supplied as its firstargument, skipping over any function defined with that name.  The`builtin' builtin executes the builtin command given as its firstargument directly. For example, to write a function to replace `cd' that writes thehostname and current directory to an xterm title bar, usesomething like the following:cd(){builtin cd "$@" && xtitle "$HOST: $PWD"}This could also be written using `command' instead of `builtin';the version above is marginally more efficient. G3) How can I find the value of a shell variable whose name is the value    of another shell variable?Versions of Bash newer than Bash-2.0 support this directly.  You can use ${!var}For example, the following sequence of commands will echo `z':var1=var2var2=zecho ${!var1}For sh compatibility, use the `eval' builtin.  The importantthing to remember is that `eval' expands the arguments you giveit again, so you need to quote the parts of the arguments thatyou want `eval' to act on. For example, this expression prints the value of the last positionalparameter:eval echo \"\$\{$#\}\"The expansion of the quoted portions of this expression will bedeferred until `eval' runs, while the `$#' will be expandedbefore `eval' is executed.  In versions of bash later than bash-2.0,echo ${!#}does the same thing.This is not the same thing as ksh93 `nameref' variables, though the syntaxis similar.  I may add namerefs in a future bash version.G4) How can I make the bash `time' reserved word print timing output that     looks like the output from my system's /usr/bin/time?The bash command timing code looks for a variable `TIMEFORMAT' anduses its value as a format string to decide how to display thetiming statistics.The value of TIMEFORMAT is a string with `%' escapes expanded in afashion similar in spirit to printf(3).  The manual page explainsthe meanings of the escape sequences in the format string.If TIMEFORMAT is not set, bash acts as if the following assignment hadbeen performed:TIMEFORMAT=$'\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS'The POSIX.2 default time format (used by `time -p command') isTIMEFORMAT=$'real %2R\nuser %2U\nsys %2S'The BSD /usr/bin/time format can be emulated with:TIMEFORMAT=$'\t%1R real\t%1U user\t%1S sys'The System V /usr/bin/time format can be emulated with:TIMEFORMAT=$'\nreal\t%1R\nuser\t%1U\nsys\t%1S'The ksh format can be emulated with:TIMEFORMAT=$'\nreal\t%2lR\nuser\t%2lU\nsys\t%2lS'G5) How do I get the current directory into my prompt?Bash provides a number of backslash-escape sequences which are expandedwhen the prompt string (PS1 or PS2) is displayed.  The full list is inthe manual page.The \w expansion gives the full pathname of the current directory, witha tilde (`~') substituted for the current value of $HOME.  The \Wexpansion gives the basename of the current directory.  To put the fullpathname of the current directory into the path without any tildesubsitution, use $PWD.  Here are some examples:PS1='\w$ '# current directory with tildePS1='\W$ '# basename of current directoryPS1='$PWD$ '# full pathname of current directoryThe single quotes are important in the final example to prevent $PWD frombeing expanded when the assignment to PS1 is performed.G6) How can I rename "*.foo" to "*.bar"?Use the pattern removal functionality described in D3.  The following `for'loop will do the trick:for f in *.foo; domv $f ${f%foo}bardoneG7) How can I translate a filename from uppercase to lowercase?The script examples/functions/lowercase, originally written by John DuBois,will do the trick.  The converse is left as an exercise.G8) How can I write a filename expansion (globbing) pattern that will match    all files in the current directory except "." and ".."?You must have set the `extglob' shell option using `shopt -s extglob' to usethis:echo .!(.|) *A solution that works without extended globbing is given in the Unix ShellFAQ, posted periodically tocomp.unix.shell.Section H:  Where do I go from here?H1) How do I report bugs in bash, and where should I look for fixes and    advice?Use the `bashbug' script to report bugs.  It is built andinstalled at the same time as bash.  It provides a standardtemplate for reporting a problem and automatically includesinformation about your configuration and build environment. `bashbug' sends its reports tobug-bash@gnu.org, whichis a large mailing list gatewayed to the usenet newsgroupgnu.bash.bug. Bug fixes, answers to questions, and announcements of new releasesare all posted tognu.bash.bug.  Discussions concerning bash featuresand problems also take place there.To reach the bash maintainers directly, send mail tobash-maintainers@gnu.org.H2) What kind of bash documentation is there?First, look in the doc directory in the bash distribution.  It shouldcontain at least the following files:bash.1an extensive, thorough Unix-style manual pagebuiltins.1a manual page covering just bash builtin commandsbashref.texia reference manual in GNU tex`info formatbashref.infoan info version of the reference manualFAQthis filearticle.mstext of an article written for The Linux Journalreadline.3a man page describing readlinePostscript, HTML, and ASCII files created from the above source areavailable in the documentation distribution.There is additional documentation available for anonymous FTP from hostftp.cwru.edu in the `pub/bash' directory.Cameron Newham and Bill Rosenblatt have written a book on bash, publishedby O'Reilly and Associates.  The book is based on Bill Rosenblatt's KornShell book.  The title is ``Learning the Bash Shell'', and the ISBN numberof the third edition, published in March, 2005, is 0-596-00965-8.  Look forit in fine bookstores near you.  This edition of the book has been updatedto cover bash-3.0.The GNU Bash Reference Manual has been published as a printed book byNetwork Theory Ltd (Paperback, ISBN: 0-9541617-7-7, Nov. 2006).  It coversbash-3.2 and is available from most online bookstores (seehttp://www.network-theory.co.uk/bash/manual/ for details).  The publisherwill donate $1 to the Free Software Foundation for each copy sold. Arnold Robbins and Nelson Beebe have written ``Classic Shell Scripting'',published by O'Reilly.  The first edition, with ISBN number 0-596-00595-4,was published in May, 2005.Chris F. A. Johnson, a frequent contributor tocomp.unix.shell andgnu.bash.bug, has written ``Shell Scripting Recipes: A Problem-SolutionApproach,'' a new book on shell scripting, concentrating on features ofthe POSIX standard helpful to shell script writers.  The first edition fromApress, with ISBN number 1-59059-471-1, was published in May, 2005.H3) What's coming in future versions?These are features I hope to include in a future version of bash.Rocky Bernstein's bash debugger (support is included with bash-3.0)associative arraysco-processes, but with a new-style syntax that looks like function declarationH4) What's on the bash `wish list' for future versions?These are features that may or may not appear in a future version of bash.breaking some of the shell functionality into embeddable librariesa module system like zsh's, using dynamic loading like builtinsa bash programmer's guide with a chapter on creating loadable builtinsa better loadable interface to perl with access to the shell builtins andvariables (contributions gratefully accepted)ksh93-like `nameref' variablesksh93-like `xx.yy' variables (including some of the .sh.* variables) andassociated disipline functionsSome of the new ksh93 pattern matching operators, like backreferencingH5) When will the next release appear?The next version will appear sometime in 2007.  Never make predictions. This document is Copyright 1995-2006 by Chester Ramey.Permission is hereby granted, without written agreement andwithout license or royalty fees, to use, copy, and distributethis document for any purpose, provided that the above copyrightnotice appears in all copies of this document and that thecontents of this document remain unaltered.-- ``The lyf so short, the craft so long to lerne.'' - Chaucer       Live Strong.  No day but today.Chet Ramey, ITS, CWRUchet@case.eduhttp://cnswww.cns.cwru.edu/~chet/

User Contributions:

Comment about this article, ask questions, or add new information about this topic:


Some parts © 2025 Advameg, Inc.  |  

[8]ページ先頭

©2009-2025 Movatter.jp