BA SH REFERENCE A liasing ...............................................................6 A rithmeticEvaluation........................................ 8 A rrays ..................................................................13 Brace Expansion................................................. 6 Built-In Commands ............................................ 16 Command Line Arguments ............................... 3 Command Substitution...................................... 8 Conditional Expressions .................................... 15 Control Commands ............................................ 14 Definitions ...........................................................2 Execution Order................................................. 13 Field Splitting..................................................... 8 Functions ............................................................12 H istory Substitution........................................... 5 Input/Output ......................................................13 Invocation and Startup ......................................3 Job Ids and Job Control..................................... 24 Options Toset.................................................... 22 Options Toshopt................................................ 23 Options Totest................................................... 21 Patterns ...............................................................9 Pre-Defined Variables ........................................10 Process Substitution.......................................... 8 Prompting ...........................................................4 Quoting ...............................................................6 Readline ..............................................................25 Readline Directives ............................................ 25 Readline Key Bindings ....................................... 25 Readline Variables ..............................................26 Restrictedbash................................................... 2 Signals and Traps ...............................................13 Special Characters.............................................. 24 Tilde Substitution............................................... 6 Variable Assignment.......................................... 9 Variable Names .................................................. 9 Variable Substitution......................................... 7 CONTENTS This referencecard w as w ritten by Arnold Robbins.W e thank ChetRamey (bashs maintainer) for his help. SpecializedSystems Consultants, Inc. (206)FOR-UNIX/(206)782-7733 FAX:(206)782-7191 E-mail: sales@ssc.com URL: http://www.ssc.com Linux JournalThe Premier LinuxMagazine Technical Books and CDs SAMBA: Integrating UNIX and W indow s Shell Tutorials, KSH Reference VI & Emacs References, VITutorial OTHER SSC PRODUCTS: ©Copyright 1999 Specialized Systems Consultants, Inc., P.O. Box 55549, Seattle, W A 98155-0549. A ll Rights Reserved. 1 This carddescribes version 2.02.0 ofbash. Several typefaces areused to clarify the meaning: Serifa Boldis used for computer input. SerifaItalic is used to indicate user input and for syntactic placeholders, s uchas variableorcmd. Serifa Roman is used for explanatory text. blank or more spaces and/or tab characters.In addition, w ords are terminated by any of the follow ing characters: ;&()|<>space tab new line command w ords. list pipelines.Can be separatedby;,&, &&,||andoptionally be terminatedby;,&. nname keyw ord bash language. Keyw ords are special only aftera;or new line, after another keyw ord, and incertain other contexts. pat bashpattern. SeePatter ns. pipeline by a pipe (|). string substitution command line w ith different text, e.g., replacing a variable w ith its value.bash performs many substitutions. This card lists them in the order they are performed. w ord necessary if it contains special characters. DEFINITIONS Ifbashis invoked as rbash,orw ith the option, itis restricted.The follow ing actions are not allow ed in a restricted shell: changing directory w ithcd setting or unsetting$SH ELLor$PATH using path names forcommands that contain/using a path name that contains/for the.command importingfunctions from theenvironment parsing$SH ELLOPTS at startup redirecting output w ithany of>,>|,<>,>&,&>,or>> usingexecto run a different command adding ordeletingbuilt-incommands w ithenable using to bypass a restricted$PATH usingset +rorset +o restricted These restrictions are in effect after executing all startupfiles, allow ing theauthorof the startup files full controlin settingup the restrictedenvironment.(In practice, restricted shells are not used much, as they are difficult to set up correctly.) RESTRICTED bash If you find an error in this referenceand are the firstto reportit, w e w ill send you a free copy of any of our references. Pleasew rite, or send electronic mail to bugs@ssc.com.Error Reporting 2 bashaccepts the one letter options to set,and the additional one letter and GNU-style long options s how n below. $bash[options][args] ends option processing ends option processing cmd execute cmd (default reads command from file named in first entry ofargs and found via path search) print all double quoted strings that are preceded by a$to stdout.This implies ,no commands areexecuted set interactive mode set restricted mode read commands from stdin (default) sameas ,butoutput in GNU gettextformat sameas display ahelp messageandexit successfully actlikea login shell do not use thereadlinelibrary to read commands w hen interactive do not read any of the initialization files. See Invocation And Startup,below do not read /.bashrc if interactive. SeeInvocation And Start up,below follow the IEEE POSIX 1003.2 standard file use fileinstead of/.bashrc if interactive sameas sameas print version information on stdoutandexit successfully COMMAND LINE ARGUMENTS Therearefive w ays thatbashruns: normal interactive, normal non-interactive, as sh,in POSIX mode, or invoked viarshd. 1. Normalinteractive: Login shells run commands in /etc/profile.The first of/.bash_profile,/.bash_login, and/.profilethat is found is executed.This stage is skipped if is used. Upon logout,bashruns /.bash_logoutif it exists. Interactive non-login shells execute /.bashrc,ifit exists. The ifileoption changes the file that is used. 2. Normal non-interactive: Non-interactive shells do variable, command, and arithmetic s ubstitution on the value of$BASH _ENV,and if the result names an existing file, that file is executed. INVOCATION AND STARTUP 3 3. Invoked as sh:Interactive login shells read and execute/etc/profileand/.profileif they exist.These files are skipped if is used.Interactive shells expand$ENV and executethatfile ifit exists. Non-interactive shells do not read any startup files. A fter the startup files areexecuted,bashenters POSIX mode. 4. POSIX mode: W hen started w ith ,interactive shells expand $ENV and executethegiven file.No other startupfiles areread. 5. Invoked viarshd:Ifrun from rshdand not invoked as sh,bashreads /.bashrc.The option skips this step, and the option changes the file, butrshd usually does not pass theseoptions on to the shellit invokes. If$SH ELLOPTS exists in theenvironment at startup, bashenables the givenoptions. INVOCATION AND STARTUP(continued) W hen interactive,bash displays the primary and secondary prompt strings,$PS1and $PS2.bash expands the follow ing escape sequences in the values ofthese s trings. \a an A SCII BEL character (octal 07) \d the date in W eekdayMonth Dayformat \e an A SCII escape character (octal 033) \h thehostnameup to the first dot (.) \H the full hostname \n anew line \r acarriage return \s the name of the shell (basenameof$0) \t the time in24-hour H H :MM:SS format \T the time in 12-hour H H :MM:SS format \u the usersusername \v the versionofbash(e.g., 2.02) \V the version andpatchlevel ofbash(e.g., 2.02.0) \w the current w orking directory \W the basename of the current w orking directory \! the history number of this command \# the command numberof this command \$ a#if the effective UID is 0, otherw ise a$ \@the time in 12-hour am/pm format \\ abackslash \nnn the charactercorresponding tooctal valuennn \[ startasequence of non-printing characters \] end a sequence of non-printing characters The history numberis the numberof the command in the history list, w hich may includecommands restored from the history file.The command number is the number of this command starting from the first command run by the current invocation of the shell. The default value ofPS1is . PROMPTING 4H istory expansion is similartocshs.Itis enabledby default in interactive shells.H istory expansion happens before the shell breaks the input into w ords, although quoting is recognized and quoted text is treated as one history w ord. H istory substitution is performed on history events, w hichconsist of an event designator(w hich previous line to startw ith), aw orddesignator(w hich w ordfrom that line to use, starting w ith zero), and one or more optionalmodifiers (w hich parts ofthe w ords to use). Colons separatethe threeparts, although the colon betw een the event designator and w ord designator may be omitted w hen the w orddesignator begins w ith ,$,*,,or%.Each modifier is s eparatedfrom the next one w itha colon.Thehistchars variable s pecifies the start-of-historyand quick substitution characters, and also the comment character that indicates that the rest of a line is acomment.The previous command is the default eventif no event designator is s upplied. Theevent designators are: ! startahistory substitution !n command linen n currentline minus n(nprevious) !! the previous command !str most recent command line starting w ith str !?str[?] most recent command line containingstr !# theentirecommand line typed so far oldnew quick s ubstitution: repeatlast command changingoldtonew The w orddesignators are: 0 the zeroth w ord (commandname) n w ordn the first argument, i.e., w ordone $ the last argument % the w ord matched by the most recent !?str?search xy w ords xthroughy. is s hortfor * w ords 1 through the last (like ) n* w ords nthrough the last (liken ) n w ords nthrough the next to last The modifiers are: e remove all but the suffix of a filename g make changes globally,use w ith s modifier,below h remove the last part ofa filename, leaving the headp print the commandbut do not execute it q quote thegenerated text r remove the last suffix of a filename s/old/new/substitutenew foroldin the text.Any delimiter may be used.An &in the replacement means the value ofold.W ith emptyold,use lastold,orthe most recent !?str?search if there w as no previous old t remove all but the last partofafilename, leaving the tailx quote thegenerated text, but break into w ords atblanks and new line & repeatthe last s ubstitution H ISTORYSUBSTITUTION 5 \c quote s ingle characterc ‘...‘ old s tylecommand substitution "..." texttreated as a s ingle argument, double quotes removed; variable, commandand arithmetic s ubstitutions performed; use\toquote$,\,‘,and" $"..." like"...",but locale translationdone ´...´ texttreated as a s ingle argument, single quotes removed; text betw eenquotes left alone, cannot include´ $´...´ texttreated as a s ingle argument,$and singlequotes removed; no substitutions performed; ANSI C andadditional escape sequences processed: \a alert(bell) \v verticaltab \b backspace \ddd octal valueddd \f form feed \xhhh hex valuehhh \n new line \\ backslash \r carriage return \e escape, not in ANSI C \t horizontal tab QUOTING alias name=value... A liases areexpanded w hen a command is read, not w hen executed.A lias names can contain any nonspecial character,not just alphanumerics, except for=. A lias expansion is doneon the firstw ordof acommand. Ifthe last characterof the replacement text is ablank, then the next w ord in the command line is checked for alias expansion.A liases can even be used toredefine shell keyw ords , but not in POSIX mode. ALIASING Brace expansion is similar to cshs.A w ord must contain at least oneunquoted left braceandcomma to be expanded.bash expands the comma-separated items in order,the result is not sorted. Brace expansions may be nested. Forexample: $mkdir /usr/{gnu,local}/{src,bin,lib} BRACE EXPANSION substitute$H OME user substituteusers home directory + substitute$PW D substitute$OLDPW D n substitute${DIRSTACK[n]}.A leading+ or is allow ed: negative values count from theend of the stack Tilde substitution happens afteralias expansion.It is done for w ords that begin w ithand for variable assignment. Invariableassignments, it is also doneafter a:in the value. Tilde substitution is done as part ofw ord expansion. This means for${nameop w ord},w ordw ill be checked for tilde substitution, butonly if the operation requires the value ofthe right-hand side. TILDE SUBSTITUTION 6 $name reference to shell variablename ${name} use braces todelimit shell variablename ${name w ord}usevariablenameif set, else usew ord ${name=w ord}as abovebut also setnametow ord ${name?w ord}usenameif set, otherw ise printw ordand exit (interactive shells do not exit) ${name+w ord}usew ordifnameis s et, otherw ise use nothing ${name[n]} elementnin arrayname ${#name} length of s hell variablename ${#name[*] } numberof elements in arrayname ${#name[@] } numberof elements in arrayname ${name#pat} remove shortest leading substring ofnamethat matches pat ${name##pat} remove longest leading substring ofnamethat matches pat ${name%pat} remove shortesttrailing substring ofnamethat matches pat ${name%%pat}remove longesttrailing substring ofnamethat matches pat ${name:start} ${name:start:length} lengthcharacters ofnamestartingat start(counting from0); use restof value if nolength.Negativestart counts from theend.Ifnameis *or@or an array indexedby*or@,start andlengthindicate the array index and count of elements.startandlengthcan be arithmeticexpressions ${name/pattern/string} value ofnamew ith first matchofpattern replaced w ithstring ${name/pattern}value ofnamew ith first matchofpattern deleted ${name//pattern/string} value ofnamew itheverymatchof patternreplaced w ithstring ${name/#pattern/string} value ofnamew ith matchofpattern replaced w ithstring;match mustoccur at beginning ${name/%pattern/string} value ofnamew ith matchofpattern replaced w ithstring;match occurs at end Note:for ,=,?,and+,usingname:insteadofname tests w hethernameis set and non-NULL; usingname tests only w hethernameis s et. For#,##,%,%%,/,//,/#,and/%,w hennameis *or@or an array indexed by*or @,the substring or substitutionoperation is applied to each element. VARIABLE SUBSTITUTION 7 A rithmetic evaluation is done w ith the let built-in command, the ((...)) command and the $((...)) expansion forproducing the result of an expression. A ll arithmeticuses longintegers. Use to get integervariables.Integerconstants look like [base#]n w herebaseis a decimal number betw een tw o and 64, andnis in that base.The digits are0-9,a-z,A-Z,_and @.A leading0or0xdenoteoctal or hexadecimal. The follow ing operators based on C, w ith the same precedenceandassociativity,areavailable. unary plus and minus !logical and bitw ise negation ** exponentiation (not in C) */% multiply,divide, modulus addition, s ubtraction << >> left shift, right shift < <=> >= comparisons == != equals, not equals & bitw ise AND bitw ise XOR | bitw ise OR && logical AND, s hortcircuit || logical OR, s hortcircuit ?: in-line conditional assignmentoperators Insidelet,((...)),and$((...)),variable names do not need a$to gettheir values. ARITHMETIC EVALUATION $(command) new form ‘command‘ old form Run command,substitute the results as arguments. Trailing new lines are removed. Characters in $IFS separate w ords (seeField Splitting). Thenew form is preferredfor simplerquoting rules. $((expression))arithmetic s ubstitution Theexpressionis evaluated, and the result is used as an argument tothe current command. COMMAND SUBSTITUTION cmd<(list1)>(list2) Runs list1and list2 asynchronously,w ith stdin and stdoutrespectively connectedviapipes using fifos or files in /dev/fd.These file names become arguments to cmd,w hichexpects toread its first argument and w rite its s econd. This only w orks if you have/dev/fdorfifos. PROCESS SUBSTITUTION Quoted text becomes one w ord. Otherw ise, occurrences of any character in $IFS separate w ords. Multiple w hitespace characters that are in$IFS do not delimit empty w ords, w hile multiple non-w hitespace characters do.W hen $IFS is not the default value, sequences of leading and trailing$IFS w hitespace characters are removed, and printable characters in $IFS surrounded by adjacent $IFS w hitespace characters delimit fields.If$IFS is NULL,bashdoes not do field splitting. FIELD SPLITTING 8? match s ingle character in filename * match0 or morecharacters in filename [chars] matchany ofchars (pair separated by a matches a range) [!chars] matchany exceptchars [chars] matchany exceptchars If the extglob option to shoptis set, the follow ing extended matching facilities may be used. ?(pat-list) optionallymatchany of the patterns *(pat-list) match0 or more of any of the patterns +(pat-list) match 1 or more of any of the patterns @(pat-list) matchexactly 1of any of the patterns !(pat-list) matchanythingbut any of the patterns pat-listis a list of one or morepatterns separatedby|. The POSIX [[=c=]]and[[.c.]]notations for same-w eight characters and collating elements areaccepted.The notation [[:class:]]defines character classes: alnum alphanumeric low er low er-case alpha alphabetic print printable blank space or tab punct punctuation cntrl control space w hitespace digit decimal upper upper-case graph non-spaces xdigit hexadecimal Threeshoptoptions affect pattern matching. dotglob include files w hose names begin w ith. nocaseglob ignorecase w hen matching nullglob remove patterns that dont match W hen expanding filenames,.and ..are ignored, filenames matching the patterns in $G LOBIGNOREare also ignored anda leading.must be supplied in the pattern to match filenames that begin w ith .. How ever,settingG LOBIGNORE enables thedotglob option. Include.* in G LOBIGNOREto get the default behavior. PATTERNS Variable names are made up of letters, digits and underscores. Theymay not startw itha digit. There is no limit on the length of a variable name, and the case ofletters is s ignificant. VARIABLE NAMES A ssignments to integer variables undergoarithmetic evaluation. Variable assignments have one of the follow ing forms. name=w ord setnametow ord name[index]=w ord set elementindexof arraynametow ord name=(w ord...)set indexed arraynametow ords name=( [num]=w ord...) set given indices of arraynametow ords VARIABLE ASSIGNMENT 9 $n usepositional parametern,n 9 ${n} usepositional parametern $* all positional parameters $@all positional parameters "$*" equivalentto"$1$2 ..." "$@" equivalentto"$1""$2"... $# numberofpositional parameters options to s hell orbyset $? value returned by last command $$ process numberofcurrent shell $! process number of last background cmd $_ nameof program in environment at startup.Value of last positional argument in last command.Nameof changed mail file in$MA ILPATH $auto_resume enables use of single-w ord commands to matchstopped jobs for foregrounding. W itha value ofexact, the w ord must exactly match the command used to s tartthe job.W ith avalue ofsubstring,the typed w ord can bea substring ofthe command, like%?string $BA SH full file name used to invokebash $BA SH _ENV in normal non-interactive shells only, value is variable, command and arithmetic substituted for path of startup file (See Invocation And Start up) $BA SH _VERSION the versionofbash $BA SH _VERSINFO[0] the major version number (release) $BA SH _VERSINFO[1] the minor version number (version) $BA SH _VERSINFO[2] the patchlevel $BA SH _VERSINFO[3] the buildversion $BA SH _VERSINFO[4] the release s tatus $BA SH _VERSINFO[5] sameas $MA CH TYPE $CDPATH search pathforcdcommand $DIRSTACK[*] array variablecontaining thepushd andpopddirectory stack $ENV in interactive POSIX mode shells, or w hen invoked as sh,value is variable, commandandarithmetic s ubstituted forpath of startup file $EUID the effective user id (readonly) $FCEDIT default editorfor thefccommand (no default value) $FIGNORE colon-separated list of suffixes giving the set offilenames to ignore w hen doing filename completion using readline $G LOBIGNORE colon-separated list of patterns giving the set offilenames to ignore w hen doing pattern matching $GROUPS[*] readonly array variable w ith the list of groups theuserbelongs to $histchars characters that control csh-style history (default: !#). See Histor y Substitution PRE-DEFINED VARIABLES 10 $H ISTCMD history number of the current command $H ISTCONTROL w itha value ofignorespace,donot enter lines that begin w ith spaces into the history file.W itha value of ignoredups,donot entera line that matches the previous line.Use ignorebothtocombineboth options $H ISTFILE w herecommand history is s tored $H ISTFILESIZE maximum numberof lines to keep in $H ISTFILE $H ISTIGNORE colon-separated list of patterns; if the currentline matches any ofthem, the line is not entered in the history file. &represents the last history line. Patterns must match the w hole line $H ISTSIZE number of previous commands to keepavailable w hilebashis running $H OME homedirectory forcdcommand and value used for tildeexpansion $H OSTFILE file in formatof/etc/hosts to use for hostnamecompletion $H OSTNAME name of the current host $H OSTTYPE string describing the current host $IFS field separators (space,tab,new line) $IGNOREEOF for interactive shells, the number of consecutive EOFs that must be enteredbeforebashactually exits $INPUTRC name of readline startup file, overrides /.inputrc $LANG name of current locale $LC_ALL currentlocale; overrides $LANG and other$LC_variables $LC_COLLATE currentlocale forcharactercollation, includes sorting results of filename expansion $LC_CTYPE current locale for character class functions (seePatter ns) $LC_MESSAGES current locale for translating $"..." strings $LINENO line number of linebeing executed in scriptor function $MA CH TYPE astring in GNU cpu-company-system format describing the machine runningbash $MA IL name of a mail file, if any $MA ILCHECK check for mail everyn seconds (60 default) $MA ILPATH filenames to check for new mail; uses :separator;filenamemay be follow ed by ?message; $_ in message is matched mail file name.Overrides $MA IL $OLDPW D previous w orking directory $OPTARG value oflast argument processed by getopts $OPTERR if set to 1, display error messages from getopts (default:1) $OPTIND indexoflast argument processedby getopts PRE-DEFINED VARIABLES (continued) 11 $OSTYPE string describing the operating system running bash $PATH command search path $PIPESTATUS[*] array variablecontaining exit status values from processes in the most recently executed foreground pipeline $PPID process id of s hellsparent $PROMPT_COMMAND command to run beforeeach primary prompt $PS1 primary prompt string ( ) $PS2 secondary prompt string (>) $PS3 select command prompt string (#?) $PS4 tracing prompt string (+) $PW D current w orking directory $RANDOM set eachtime its referenced, $REPLY set by the select and read commands $SECONDS numberof seconds s ince shell invocation $SH ELL name of this s hell $SH ELLOPTS colon-separated list of the enabled shell options forset $SH LVL incrementedby one for each sub-bash $TIMEFORMAT format string for output of time keyw ord. Special constructs introducedby%. %[p][l]R elapsed secs %[p][l]U user CPU secs %[p][l]S system CPU secs %P CPU percentage %% literal% Optionalpgives the precision, the numberofdigits after the decimal point; it must be betw een 0and 3.Optionall produces a longerformat, in the formMMmSS.FFs $TMOUT number of seconds to w ait during prompt before terminating $UID the real user id (readonly) PRE-DEFINED VARIABLES (continued) Functions run in the same process as the calling script, and sharethe open files and current directory.They access their parameters likea script, via$1,$2 and so on.$0does not change.return may be used inside a function or.script. Functions share traps w ith the parent script, except forDEBUG.Functions may be recursive, and may have local variables, declaredusing declare,local,ortypeset.Functions may beexported intotheenvironment w ith . FUNCTIONS 12Redirections aredone left toright, afterpipes are set up. Defaultfiledescriptors arestdin andstdout.File descriptors above 2 are marked close-on-exec. &>w ord sendstdoutandstderrtow ord >&w ord sendstdoutandstderrtow ord [n]file usefileforoutput [n]>|file like>,butoverrides noclobber [n]>>file like>but append tofileif it exists [n]<>file open fileforread/w rite (default: fd0) [n]<&m duplicate input filedescriptorfromm [n]>&m duplicateoutput filedescriptorfromm [n] close input filedescriptor [n] close output filedescriptor [n]<and>&,the first is preferred. Itis equivalentto >w ord2>&1. INPUT/OUTPUT A ll substitutions and I/O redirections are performed beforea command is actually executed. bash maintains an internal hash table for caching external commands.Initially,this table is empty.As commands arefound by searching the directories listed in $PATH,they areadded to thehash table. The command search order is s hell functions first, builtincommands s econd, andexternal commands (first in the internal hash table, and then via$PATH)third. EXECUTION ORDER Signal handling is done w ith thetrapbuilt-in command. Thew ord argument describing code to executeupon receiptofthe signalis scanned tw ice bybash;once w hen thetrap command is executed, and again w hen the signalis caught.Therefore itis besttouse single quotes for thetrap command. Traps areexecuted in orderof signal number.Youcannot change the status of a s ignal that w as ignored w hen the shell startedup. Traps onDEBUG happen aftercommands areexecuted. Backgrounded commands (those follow ed by&)w ill ignore theSIG INTandSIGQUIT signals if themonitor option is turned off.Otherw ise, they inherit the values of the parentbash. SIGNALS AND TRAPS A rrays in bash have no limits on the number of elements. A rrayindices startat0.A rray subscripts can bearithmeticexpressions.A rray elements need not be contiguous.bashdoes not have associative arrays. ARRAYS 13 !pipeline executepipeline.Ifexit status w as non-zero, exit zero. Ifexit status w as zero, exit 1 casew ordin [[(]pat 1[|pat 2]...)list;;]...esac executelistassociated w ithpatthat matches w ord. Field splitting is not done forw ord.patis abash pattern (seePatter ns).|is used to indicatean OR condition. Useleading(ifcaseis inside$( ) forname[in w ords];dolist;done sequentially assign eachw ordtonameandexecute list.If in w ords is missing use the positional parameters [function]func() {list;} define functionfunc,body is list(seeFunctions) iflist1;then list2[;eliflist3;then list4]...[;elselist5];fi if executing list1returns successful exit status, executelist2else ... selectname[in w ords];dolist;done print a menuofw ords,prompt w ith$PS3 and read a line from stdin,saving itin $REPLY.Ifthe line is the number of oneof the w ords, setnameto it, otherw ise setnameto NULL.Executelist.Ifin w ords is missing use the positional parameters. bashautomatically reprints the menu at theendof the loop time[ ]pipeline executepipeline;print elapsed, system and user times onstderr.print times in POSIX format The$TIMEFORMAT variablecontrols the formatof the outputif is not used.bashuses the value $\nreal\t%3lR\nuser\t%3lU\nsys\t%3lSif there is novalue for$TIMEFORMAT untillist 1;dolist 2;done likew hilebut negatethe termination test w hilelist 1;dolist 2;done execute list 1.Iflast command in list 1had a successful exit status, execute list 2 follow ed by list 1.Repeat until last command in list 1returns an unsuccessful exit status ((...))arithmeticevaluation, likelet "..." [[expression]] evaluateexpression,return successful exit status if true, unsuccessful if false (see Conditional Expressions fordetails) (list)executelistin a sub-shell {list;} executelistin the current s hell CONTROL COMMANDS 14 Used w ith the[[...]]compound command, w hichdoes not dopattern expansion or w ord splitting. string true ifstringis not NULL file true iffileexists ( is preferred) file true iffileis a block device file true iffileis acharacter device file true iffileis a directory file true iffileexists file true iffileis a regularfile file true iffilehas s etgid bit set file true iffilegroup is effective gid file true iffileis a s ymbolic link file true iffilehas s ticky bit set file true iffileis a s ymbolic link string true ifstringhas non-zero length file true iffileexists and w as modified since last read option true ifoptionis on file true iffileow ner is effective uid file true iffileis a fifo (named pipe) file true iffileis readable file true iffilehas non-zero s ize file true iffileis a socket filedes true iffiledes is a terminal file true iffilehas s etuid bit set file true iffileis w ritable file true iffileis executable string true ifstringhas zero length file1 file2 true iffile1is new er than file2orfile2 does not exist file1 file2 true iffile1is older than file2orfile2 does not exist file1 file2 true iffile1andfile2are the same file string==patterntrue ifstringmatches pattern string!=patterntrue ifstringdoes not matchpattern string1string2true ifstring1is afterstring2 exp1 exp2 true ifexp1equals exp2 exp1 exp2 true ifexp1does not equalexp2 exp1 exp2 true ifexp1is less than exp2 exp1 exp2 true ifexp1is greater thanexp2 exp1 exp2 true ifexp1is less than orequaltoexp2 exp1 exp2 true ifexp1is greater thanor equaltoexp2 (expression) true ifexpressionis true, for grouping !expression true ifexpressionis false exp1&&exp2 true ifexp1AND exp2are true exp1||exp2 true ifexp1ORexp2is true Iffileis /dev/fd/n,then, ifthere is no/dev/fddirectory, file descriptor n is checked.Otherw ise, the real /dev/fd/nfile is checked. Linux, FreeBSD, BSD/OS (and maybe others) return info for the indicated file descriptor,instead of the actual/dev/fddevice file. Both && and || are short circuit. Operands of comparison operators undergoarithmetic evaluation. For==and!=,quoteany partofpattern totreat it as a string.CONDITIONAL EXPRESSIONS 15 Thesecommands areexecuteddirectly by the shell. A lmost all accept to mark theend of options. .file sourcefile read and execute commands from file.If arguments, save and restore positional params. Search$PATH ;ifnothing found, look in the current directory : null command; returns 0exit status [ seetest alias [ ][name[=value]...] create an alias.W ith no arguments, print all aliases. W ithname,print alias value forname printalias beforeeach alias bg[jobid] putjobidin the background bind[ map][ ] bind[ map][ func][ keyseq][ func] bind[ map] file bind[ map]keyseq:func display and/or modifyreadlinefunction and key bindings. The s yntax is s ame as for/.inputrc file read new bindings from file list the names of allreadlinefunctions map use the keymapmap listreadlinefunctions and bindings for re-reading listreadlinefunctions and bindings func show w hich keys invokefunc keyseq remove bindings forkeyseq listreadlinekey sequences and macros for re-reading listreadlinekey sequences and macros func remove key bindings forfunc listreadlinevariable names and values for re-reading listreadlinevariable names and values break[n] exit from enclosingfor,w hile,untilorselectloop. Ifnis s upplied, exit from nthenclosing loop builtin shell-builtin[args ...] execute shell-builtin w ith given args and return status. Usefulfor the body of ashell function that redefines a built-in, e.g.,cd cd[ ][dir] change current directory to dir($H OME default). Do directory path search using value of$CDPATH use logical path forcd ..,$PW D (default) usephysical path forcd ..,$PW D If bothare given, the lastoneon the command line w ins cd[ ] change current directory to$OLDPW D command[ ]name[arg...] w ithout or ,executenamew ith arguments arg usea default search path, not$PATH print a one w orddescriptionofname print a verbosedescriptionofname continue[n] do nextiteration of enclosingfor,w hile,untilor selectloop. Ifn is s upplied, iteratenthenclosing loop BUILT-IN COMMANDS 16declare[afFirx][ ][name[=value]] typeset[afFirx][ ][name[=value]] set attributes and values of variables.Inside functions, create new copies ofthe variables.Using +insteadof turns attributes off.W ith no names or attributes, print every variables name and attributes nameis an array eachnameis a function dont show function definitions (bodies) nameis an integer; arithmetic evaluation is doneupon assignment marknames readonly marknames forexport dirs [ ][+n][n] display the directory stack +n show nthentry from left,n 0 n show nthentry from right,n 0 clear the directory stack print a longer format listing print the stackoneentry per line print the stackoneentry per line, w ith index numbers disow n[ ][ ][job...] w ith nooptions, remove namedjobs from the table of active jobs remove or mark(w ith )all jobs mark eachjobtonotreceive aSIG HUP w henbashterminates use w ith to mark just running jobs echo[ ][w ords] echow ords; is not s pecial expand \-escapes (seeecho(1)) neverexpand \-escapes dont outputtrailing new line printfis moreportable enable[ ][ file][name...] enable and disable shell built-ins, or load and unload new built-ins from shared library files. Disabling abuilt-in allow s use of a disk file w ith the same name as a built-in print all built-ins, w ith their status deletea built-in loaded w ith file loada new built-innamefrom file disablename,orprint disabledbuilt-ins w ith nonames print enabledbuilt-ins printonly POSIX special built-ins eval[w ords] evaluatew ords and executeresult exec[ name][ ][w ords] executew ords in placeofthe shell.Ifredirections only,change the shells open files usenameforargv[0] clear theenvironment first place a onargv[0](likelogin(1)) Iftheexecfails, non-interactive shells exit, unless theshoptoption execfailis s et exit[n] exit w ith returnvaluen.Use$? if non BUILT-IN COMMANDS (continued) 17 export[ ][name[=value]...] w ith no arguments, print names and values of exportedvariables. Otherw ise,expor tnames to the environmentofcommands names refer tofunctions stop exporting eachname printexportbeforeeachvariable fc[ editor][ ][first[last]] print a range ofcommands from firsttolastfrom last $H ISTSIZEcommands runeditorif supplied; if not, use first of $FCEDIT,$EDITOR,orvion commands; executeresult(s) list on s tandardoutput instead of editing dont printline numbers reverseorderofcommands [old=new ][command] substitutenew foroldin command(orlast command if nocommand)andexecute the result fg[jobid] putjobidin the foreground getopts optstring name[arg...] parseparameters andoptions (seebash(1)) hash[ ][ file][name] w ithno arguments, print thehash tablecontents, giving hit count and file name file enterfilefornamein thehash table clear the internal hash table A ssignmentto$PATH also clears thehash table help[pattern] print help.W ithpattern,print help about all the commands that matchpattern history[n] [file] history[ ] arg[...] arg[...] w ithno options, print the command history.An argumentofnprints onlyn lines. Ifsupplied, use fileinsteadof$H ISTFILE appendnew history lines to history file clear the history list read new history lines in the file intothe internal history list perform history substitution and print the results replace internal history w ithcontents of history file place theargs into the history list for lateruse w rite the internal history to the file jobs [ ][jobid...] command[args ...] list information about jobs also list process id only list stopped orexited jobs only list process groups only list running jobs only list stopped jobs replace anyjobidin the command line w ith the corresponding process group ID, andexecute the command BUILT-IN COMMANDS (continued) 18 kill[sig]jobid... kill[ signame][ signum]jobid... send SIG TERM or given signal to namedjobids. Signals are names listed in /usr/include/signal.h w ithor w ithout the prefix SIG . Stoppedjobs get aSIGCONT first if sig is either SIG TERM or SIG HUP [sigs ...] list signal names and/or numbers.If sig is a numerical exit status, print the signal that killed the process let arg... evaluateeachargas an arithmeticexpression; exit 0 if the last expression w as non-zero, 1 otherw ise (seeArithmeticEvaluation) local[name[=value]...] createvariables w ith thegiven values localtoa function. W ith no operands , print a list of local variables. Mustbe used inside a function logout exit a login shell popd[ ][+n][n] removeentries from the directory stack.W ith no arguments, remove the top entry andcdthere +n removenthentry from left,n 0 n removenthentry from right,n 0 dont change directory printfformat[arg...] printoutput like ANSI C printf,w ithextensions %b expand escape sequences in s trings %q print quoted string that canbe re-read Formatconversions arereused as needed pushd[ ][dir] pushd[ ][+n][n] add an entry to the directory stack.W ith no arguments, exchange the top tw o entries +n rotate the stack sothatthenth entry from left is at the top,n 0 n rotate the stack sothatthenth entry from right is at the top,n 0 dont change directory dir pushdiron the stackandcdthere pw d[ ] print w orking directory name print logical path (default) print physical path If bothare given, the lastoneon the command line w insname][ ][ prompt][names ...] readstdin and assign tonames.$IFS splits input. $REPLY is s et if nonamegiven. Exit0unless endof-file encountered read w ords into indexed arrayname usereadlineif reading from a terminal printpromptif reading from a terminal beforereading at end of linedoes not do line continuation BUILT-IN COMMANDS (continued) 19 readonly[ ][name=value...] marknames read-only; printlist if nonames eachnamemust be an array eachnamemust be a function printreadonlybeforeeachvariable return[n] exit functionor.script w ith returnvaluen.W ith no n,return s tatus oflastcommand.If not in function or.script, print an error message set[options][ option][w ords] set flags and options (seeOptions Toset).w ords set positional parameters set[+options][+ooption][w ords] unset flags and options shift[n] renamepositional parameters; $n+1=$1 ... ndefaults to 1 shopt[ ][option...] print or change values ofshell options.W ith no arguments, print s hell option information only change options print s ettings forre-reading quiet mode; exit status indicates option status set (enable) givenoption; w ith no options, print those that are set unset (disable) givenoption; w ith no options, print those that areunset (SeeOptions Toshopt) suspend[ ] suspend the shell untilSIGCONTis received force suspension, even for login shell testevaluate conditional expressions (see Options To testandConditional Expressions) times print accumulated process times trap[ ][w ord][sigs] execute w ord if signalin sigs received.sigs are numbers orsignal names w ithor w ithout SIG . W ith no w ord orsigs,print traps.W ith no w ord, resetsigs to entry defaults.Ifw ord sigs to entry defaults.Ifw ordis the null string, ignore sigs.Ifsigs is 0orEXIT,executew ordon exit from shell. If sigs is DEBUG,run w ord after every command.print a list of signal names andnumbers printtraps w ith quoting type[ ]name... describehow the shell interprets name print all possible interpretations ofname print the name of the file to execute if nameis an external program print akeyw orddescribingname BUILT-IN COMMANDS (continued) 20ulimit[type][options][limit] setor print per-process limits type(default is both): hard limit soft limit options: all (display only) corefile size kofdata segment maximum file s ize kofphysical memory maximum filedescriptor + 1 size of pipebuffers kofstack segment cpu seconds max processes foroneuser kofvir tualmemory is assumed if nooptions aregiven.The size for is in 512-byteblocks; the others are in s izes of 1024 bytes umask[ ][mask] set file creationpermissions mask tocomplementof maskif octal, or s ymbolicvalue as in chmod.W ith no arguments, print current mask.An octal mask is permissions to remove, a symbolic mask is permissions to keep printoutputforre-reading print current mask in s ymbolic form unalias [ ][names] remove aliases names remove all aliases unset[ ][names] unsetvariables names (sameas ) unset functions names unsetvariables names Unsetting LINENO, MA ILCHECK, OPTARG, OPTIND,RANDOM,SECONDS,TMOUT and _ removes their special meaning, even if used afterw ards w ait[jobid...] w ait for jobjobid;ifnojob,w ait for all children BUILT-IN COMMANDS (continued) Thetestcommand, and its synonym [...],arebuilt-in to bash.The command accepts all ofthe options listed in theConditional Expressions section. H ow ever,since itis acommand, options and arguments must bequoted to get proper behavior,and normal pattern expansion and field splitting aredone.Parentheses used for grouping must bequoted.A rithmeticexpansion is not done for numericoperators, andpattern matching is not done for==and!=.testcomplies w ithPOSIX. The and options have the follow ing meanings, instead of the ones listed in Conditional Expressions: logical AND logical OR OPTIONS TO test 21 Thesetcommand is complicated.H ere is asummary. Use +instead of to turn options off.W ith no arguments,set prints the names and values of all variables. set[abBCefhHkmnpPtuvx][ooption...] [arg...] automatically exportvariables upon assignment print job completion messages immediately,dont w ait for nextprompt enable braceexpansion (default) force>|tooverw rite for existing files exit uponnon-zeroexit from acommand disablepattern expansion savecommand locations in the internal hash table(default) enable!-style history (default) place all variable assignments in theenvironment (obsolete) run background jobs in their ow n process group, print a message w hen they exit; set automatically for interactive shells on job control systems readcommands w ithout executing them (ignored if interactive) setoptions; w ith no arguments, print current s ettings allexport sameas braceexpand sameas emacs useanemacs-style line editor (default) errexit sameas hashall sameas histexpand sameas history enable history ignoreeof likeIGNOREEOF=10 keyw ord sameas monitor sameas noclobber sameas noexec sameas noglob sameas notify sameas nounset sameas onecmd sameas physical sameas posix obey the POSIX 1003.2 standard privileged sameas verbose sameas vi use avi-style lineeditor xtrace sameas dont read$ENV,donot take shell functions from environment, and ignore options in $SH ELLOPTS environment variable follow the physical directory structure forcommands that change the directory readandexecuteonecommand, then exit make it an error to substitutean unset variable print inputlines as theyreread OPTIONS TO set 22 print commands as theyreexecuted, preceded by expanded value of$PS4. Output is quotedfor laterreuse turn off , ,stop looking forflags; any remaining args setthe positional parameters do not change flags; s etpos itional parameters from argumentlist; w ith no args, unset the positional parameters OPTIONS TO set(continued) Theshoptcommand sets or unsets a number of options that affect how bashbehaves. This section describes each options effect w hen enabled.Unless noted, they are all disabled by default. cdable_vars treat an argumenttocdthat is not adirectory as a variable w hosevalue is the directory name cdspell attempt to correct minor spelling errors in arguments to cd.Errors tried are transposed characters, a missing character or an extra character.Only obeyed in interactive shells checkhash check that acommand in thehash table s till exists before trying to execute it.If it doesnt, search $PATH checkw ins ize check the w indow sizeaftereachcommandand update$LINESand$COLUMNS cmdhist attempt to save alllines of a multi-line command in the history file as one line, for easy re-editing dotglob include files w hose names begin w ith.in path expansions execfail keep non-interactive shells from exiting w hen exec fails expand_aliases expand aliases as described in Aliases.Enabled automatically in interactive shells extglob enable theextended pattern matching facilities (see Patter ns) histappend append the current history to$H ISTFILEupon exit, instead of overw riting it histreedit if usingreadlineanda history substitution fails, the usercan re-edit the line histverify if using readline,load the results of history substitution intoreadlinefor furtherediting hostcomplete if usingreadline,attempt host completionon w ord containing@huponexit sendSIG HUPto all jobs w henbashexits interactive_comments in interactive shells, a w ord starting w ith#starts a comment. Enabledby default OPTIONS TO shopt 23 lithist if cmdhist is also enabled, save multi-line commands w ith new lines, not semi-colons mailw arn print a w arning message if a filebeing checked for mail w as accessed since the last time it w as checked nocaseglob do a case-insensitive match w hen expanding pathnames nullglob remove patterns that dont matchany file, instead ofleaving them unchanged in the command line promptvars do parameterexpansion on theprompt variables beforeprinting them.Enabled by default shift_verbose print an error message w hen the shift count is greater thanthe numberof positional parameters sourcepath use$PATH tofind shell files given tothe.and sourcecommands. Enabledby default OPTIONS TO shopt(continued) # startofcomment; terminated by new line | (pipe) connects tw ocommands ; command separator & run process in background; defaultstdin from /dev/nullif no job control && only run follow ing command if previous command completed successfully || only run follow ing command if previous command failed ´ enclose s tring tobe taken literally " enclose s tring to havevariable, command and arithmetic s ubstitutiononly $( ) in-line command substitution (new style) ‘ in-line command substitution (old s tyle) ((...)) arithmeticevaluation, likelet "..." $((...)) in-line arithmeticevaluation \ treat follow ing character literally \new line line continuation SPECIAL CHARACTERS Jobs canbe represented as follow s: jobid the job identifierfor ajob, w here: %% current job %+ current job previous job %?str job uniquely identifiedbystr %n job numbern %pref job w hosecommand linebegins w ithpref Usually,aprocess ID may be used insteadofajobid. Commands that take ajobiduse the currentjob if no jobidis s upplied. Traps on SIGCH LD execute w henevera job completes. The commands fgandbgareonly available on s ystems that support job control.This includes Linux, BSD systems, System V Release 4, and most UNIX s ystems. JOB IDS AND JOB CONTROL 24Thereadlinelibrary implements command lineediting. By default, it provides an emacs editing interface, although a vi interface is available.readline is initialized eitherfrom the file namedby$INPUTRC (if set), or from /.inputrc.In that file, you can use conditionals, define key bindings for macros and functions, and setvariables. From thebashlevel, thebindcommand allow s you to add, remove and change macro and key bindings. Therearefive input mode map names that control the action taken for each input character.The map names areemacs,emacs-standard,emacs-meta,emacs-ctlx, vi,vi-command,andvi-insert.emacs is the sameas emacs-standard,andviis the sameas vi-command. Youchoose w hicheditor you prefer w ith or in your/.bashrcfile, or atruntime. readlineunderstands the character names DEL,ESC, LFD,NEWLINE,RET,RETURN,RUBOUT,SPACE,SPC and TAB. REA DLINE Directives in the.inputrc fileprovide conditional and include facilities s imilarto the C preprocessor. $include includea file, e.g., a s ystem-w ide/etc/inputrcfile $ifstart aconditional, for terminal or application specific s ettings.Youcan test the follow ing: application= test theapplication, e.g.bashorgdb mode= test theediting mode,emacs orvi term= test the terminal type The useofapplication=is optional; e.g.,$if Bash $else startthe elsepar tof aconditional $endif finisha conditional REA DLINE DIRECTIVES Keys bound to a macro place the macro text into the input; keys bound to a function run the function. Youcan use theseescape sequences in bindings: \a alert(bell) \r carriage return \b backspace \t horizontal tab (TAB) control prefix \v verticaltab \d delete(DEL) \\ backslash \e escape (ESC) \" literal" \f form feed \´ literal´ meta prefix \ddd octal valueddd \n new line \xhhh hex valuehhh Macros and function bindings look like: macro: key-seq:"text" function: key-seq:function-name Macros have quoted text on the right of the colon; functions have function names.A key-seqis eithera singlecharacterorcharacter name(suchas ), or a quoted string of characters (single or double quotes). REA DLINE KEY BINDINGS 25 Variables control different aspects of readlines behavior.You set a variable w ith setvariablevalue Unless otherw ise noted,valueshouldbeeitherOn or Off.The descriptions below describe the effect w hen the variable is On.Default values are show n in parentheses. bell-style(audible) defines how readlineshould ring the bell: audible ring the bell none never ring the bell visible flash the screen comment-begin(#) insert this string for readline-insert-comment, (bound toM-#inemacsmodeand to#in vimode) completion-ignore-case(Off) ignorecase w hen doing completions completion-query-items (100) if the numberofcompletion items is less than this value, place them in the command line. Otherw ise, ask the userif they should be s how n convert-meta(On) treat characters w ith the eighthbit set as the meta version oftheequivalent s even bit character disable-completion(Off) do not do completion editing-mode(emacs) set the initial editing mode. Possible values are emacs orvi enable-keypad(Off) attempt to enable theapplication keypad.This may be needed to make the arrow keys w ork expand-tilde(Off) attempt tildeexpansion as partofw ordcompletion input-meta(Off) meta-flag(Off) enable eight bit input.The tw ovariable names are synonyms keymap(emacs) set the current keymap. SeeReadlinefor a list of allow ed values.The editing-mode variable also affects the keymap mark-directories (On) append a/tocompleted directory names mark-modified-lines (Off) place a*at the frontof modified history lines output-meta(Off) print characters w ith the eighthbit set directly,not as M-x print-completions-horizontally(Off) display completions horizontally,w ith the matches sortedalphabetically,instead of vertically dow n the screen show -all-if-ambiguous (Off) immediately list w ords w ith multiple possible completions, instead ofringing the bell visible-stats (Off) w hen listing possible completions, append a character that denotes the files type REA DLINE VARIABLES More information aboutreadlinecan be foundon-lineat http://w w w .ssc.com/ssc/bash. 26