Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Standard view
Full view
of .
Save to My Library
Look up keyword
Like this
0 of .
Results for:
No results containing your search query
P. 1
Bash Quickref

Bash Quickref

Ratings: (0)|Views: 342|Likes:
Published by rtr7777

More info:

Published by: rtr7777 on Mar 31, 2010
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less





(206)FOR-UNIX/(206)782-7733FAX: (206)782-7191E-mail: sales@ssc.comURL: http://www.ssc.comLinux Journal—The Premier Linux MagazineTechnical Books and CDsSAMBA: Integrating UNIX and WindowsShell Tutorials, KSH ReferenceVI & Emacs References, VI TutorialOTHER SSC PRODUCTS:©Copyright 1999 Specialized Sstems Consultants, Ic.,P.O.Box 55549,Seattle,WA98155-0549.  AllRightsReserved.1This card describes vesion 2.02.0 ofbash. Seveal typeaces ae used to clarify themeaning: •Seifa Boldis usedor computerinput.
Serifa Italicis used to indicate user input and for  syntactic placeholders, such asvariableorcmd.Serifa Roman is used for explanatory text. blank or more spaces and/or tab characters.In addition,words are terminated by any of the following characters:;&()|<>space tab newlinecommandwords. listpipelines.Can be separated by;,&,&&,||and optionally be terminated by;,&. n name keywordbashlanguage.Keywords are special only after a;or newline, after another keyword, and incertain other contexts. patbashpattern. See
Patter ns.
 pipeline by a pipe (|). string  substitutioncommand line with different text, e.g., replacing avariable with its value.bashperforms man substitutions. This card lists them in the order they are performed.word necessary if it contains special characters. DEFINITION Ifbashis invoked asrbash,orwith theoption, it is restricted.The following actions are not allowed in a restricted shell:changing directory withcd setting or unsetting$SHELLor$PATHusing path names for commands that contain/using a path name that contains/for the.command importingfunctions from the environment  parsing$SHELLOPTSat startup redirecting output with any of>,>|,<>,>&,&>,or>>usingexecto run a different commandadding or deleting built-in commands withenableusingto bypass a restricted$PATHusingset +rorset +o restrictedThese restrictions are in effectafterexecuting al startupfiles, allowing the author of the startup files full control in setting up the restricted environment.(In practice, restricted shells are not used much, as they are difficult to set up correctly.) RESTRICTED
bashIfyou indan eror n this reference and ae theirst to reportit,we willsend you a reecopy of any of our references. Peasewrite, or send eectronc mail to bugs@ssccomError Reporting2bashaccepts the oneetter optons tosetandthe addtiona oneetter andNUstyle ong options shown beow.$bash[
options][args]ends option processing ends option processing cmdexecutecmd(default readscommand from file named in first entry ofargsand found via path search) print all double quotedstringsthat are preceded by a$to stdout.This implies,nocommands are executed set interactive mode set restricted mode read commands fromstdin(default) same as,but output in GNU gettextformat  same asdisplay a help message and exit  successfully act like a login shell do not use thereadlinelibrary to read commands when interactivedo not read any of the initialization files.See
Invocation And Startup,belowdo not read˜/.bashrcifinteractive. SeeInvocation AndStar tup,belowfollow the IEEE POSIX 1003.2standard
 fileusefileinstead of˜/.bashrci interactive same as same as print version information on stdoutand exit successfully COMMAND LINE ARGUMENTThere are five ways thatbashruns: normal interactive, normal non-interactive, assh,inPOSIX mode, or  invoked viarshd.1. Normal interactive: Login shells run commands in/etc/profile.The first of˜/.bash_profile,˜/.bash_login,and˜/.profilethat is found is executed.This stage is skipped ifis used.Upon logout,bashruns˜/.bash_logoutif it exists. Interactive non-login shells execute˜/.bashrc,ifit exists. Theifileoption changes the file that isused.2. Normal non-interactive: Non-interactive shells dovariable, command, and arithmetic substitution on thevalueof$BASH_ENV,and if the result names anexisting file, that file is executed. INVOCATION AND STARTU33. Invoked assh:Interactive login shells read andexecute/etc/profileand˜/.profileif they exist.These files are skipped ifis used.Interactive shells expand$ENVand execute that file if it exists. Non-interactive shells do not read any startup files. After the startup files are executed,bashenters POSIX mode.4. POSIX mode: When started with,interactive shells expand$ENVand execute the given file.Noother startup files are read.5. Invoked viarshd:Ifrun fromrshdand not invoked as sh,bashreads˜/.bashrc.Theoption skips this step, and theoption changes the file, butrshdusually does not pass these options on to the shell it  invokes. If$SHELLOPTSexists in the environment at startup, bashenables the given options. INVOCATION AND STARTUP(continued)When interactive,bashdisplays the primary and secondary prompt strings,$PS1and$PS2.bashexpands the following escape sequences in the valuesof these strings.\aan ASCII BEL character (octal 07)\dthe date in Weekday Month Day’’format \ean ASCII escape character (octal 033)\hthe hostname up to the first dot (.)\Hthe full hostname\nanewline\racarriage return\sthe name of the shell (basename of$0)\tthe time in 24-hour HH:MM:SS format \Tthe time in 12-hour HH:MM:SS format \uthe usersusername\vthe version ofbash(e.g., 2.02)\Vthe version and patchlevel ofbash(e.g., 2.02.0)\wthe current working directory \Wthe basename of the current working directory \!the history number of this command\#the command number of this command\$a#if the effective UID is 0, otherwise a$\@the time in 12-hour am/pm format \\abackslash\nnnthe character corresponding to octal valuennn\[startasequence of non-printing characters\]end a sequence of non-printing charactersThe history number is the number of the command inthe history list, which may include commands 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 ‘. PROMPTING4
events,which consist of anevent designator(which previous lineto startwith), aword designator(which word from that  line to use, starting with zero), and one or moreoptionalmodifiers(which parts of the words to use).Colons separate the three parts, although the colon between the event designator and word designator  may be omitted when the word designator begins withˆ,$,*,,or%.Each modifier is separated from the next one with a colon.Thehistcharsvariable specifies the start-of-historyand quick substitution characters, andalso the comment character that indicates that the rest of a line is a comment.The previous command is thedefault event if no event designator is supplied.The event designators are:!startahistory substitution!ncommand linen ncurrent line minusn(nprevious)!!the previous command!strmost recent command line starting with str !?str[?]most recent command line containingstr !#the entire command line typed so faˆoldˆnequick substitution: repeat last commandchangingoldtonew The word designators are:0the zeroth word (command name) nwordnˆthe first argument, i.e., word one$the last argumen%the word matched by the most recen!?str?search xywordsxthroughy.is shortfo*words 1 through the last (like) n*wordsnthrough the last (liken) nwordsnthrough the next to lasThe modifiers are:eremove all but the suffix of a filenamegmake changes globally,use withs modifier,below  hremove the last partofafilename, leaving the ‘‘head’ pprint the command but do not execute iqquote the generated tex rremove the last suffix of a filename s/old/new/substitutenewforoldin the text.Any delimiter may be used.An&in the replacement means the value ofold.Withemptyold,use lastold,orthe most recent !?str?search if there was no previousoldtremove all but the last partofafilename, leaving the ‘‘tail’ xquote the generated text, but break intowords atblanksand newline&repeat the last substitutionHISTORYSUBSTITUTIO\cquote single characterc`...`old style command substitution"..."text treated as a single argument, doublequotes removed; variable, command andarithmetic substitutions performed;use\to quote$,\,`,and"$"..."like"...",but locale translation done´...´text treated as a single argument, singlequotes removed; text between quotes left alone, cannot include´$´...´text treated as a single argument,$and single quotes removed; no substitutions performed; ANSI C and additional escape sequences processed:\aalert(bell)\vverticaltab\bbackspace\dddoctal valueddd\fform feed\xhhhhex valuehhh\nnewline\\backslash\rcarriage return\eescape, not in ANSI C \thorizontal tabQUOTINGaliasname=value... Aliases are expanded when a command is read, not when executed.Alias names can contain any non- special character,not just alphanumerics, except for=. Alias expansion is done on the firstwordof a command. If the last character of the replacement text is ablank,then the next word in the command line is checked for alias expansion.Aliases can even be used to redefine shell keywords, but not in POSIX mode. ALIASING Brace expansion is similar tocsh’s.Aword must contain at least one unquoted left brace and comma to be expanded.bashexpands the comma-separated items in order,the result is not sorted. Braceexpansions may be nested. For example:$mkdir /usr/{gnu,local}/{src,bin,lib} BRACE EXPANSIO˜substitute$HOM˜usersubstituteusers home directory ˜+substitute$PWD substitute$OLDPWD˜nsubstitute${DIRSTACK[n]}.Aleading+oris allowed: negative values count  from the end of the stack Tilde substitution happens after alias expansion.It isdone forwordsthat begin with˜and for variableassignment. In variable assignments, it is also done after a:in thevalue. Tilde substitution is done as partofwordexpansion. This means for${name op word},wordwill bechecked for tilde substitution, but only if the operation requires the value of the right-hand side.TILDE SUBSTITUTIO6$namereference to shell variablename${name}use braces to delimit shell variablename${nameword}use variablenameif set, else useword${name=word}as above but also setnametoword${name?word}usenameif set, otherwise printwordandexit (interactive shells do not exit)${name+word}usewordifnameis set, otherwise use nothing ${name[n]}elementnin arrayname${#name}length of shell variablename${#name[*] }number of elements in arrayname${#name[@] }number of elements in arrayname${name#pat}remove shortest leading substring ofnamethat matchespat ${name##pat}remove longest leading substrinofnamethat matchespat ${name%pat}remove shortest trailing substring ofnamethat matchespat ${name%%pat} remove longest trailing substring ofnamethat matchespat ${name:start}${name:start:length} lengthcharacters ofnamestartingat  start(counting from0); use rest of value if nolength.Negativestart counts from the end.Ifnameis*or@or an array indexed by*or@,start andlengthindicate the array index andcount of elements.startandlengthcan be arithmetic expressions${name/pattern/string}value ofnamewith first match ofpattern replaced withstrin${name/pattern}value ofnamewith first match ofpatterndeleted${name//pattern/string}value ofnamewith every match of  patternreplaced withstrin${name/#pattern/string}value ofnamewith match ofpattern replaced withstring;match must occur at beginning ${name/%pattern/string}value ofnamewith match ofpattern replaced withstring;match occurs at end Note:for,=,?,and+,usingname:instead ofnametests whethernameis set and non-NULL; usingnametests only whethernameis set. For#,##,%,%%,/,//,/#,and/%,whennameis*or@or an array indexed by*or@,the substring o substitution operation is applied to each element.VARIABLE SUBSTITUTIO7 Arithmetic evaluation is done with theletbuilt-incommand, the((...))command and the$((...))expansion for producing the result of an expression. All arithmetic useslongintegers. Useto ge integer variables.Integer constants look like [base#]nwherebaseis a decimal number between two and 64,andnis in that base.The digits are0-9,a-z,A-Z,_and@.Aleading0or0xdenote octal or hexadecimal.The following operators based on C, with the same precedence and associativity,are available.unary plus and minus!˜logical and bitwise negation**exponentiation (not in C)*/%multiply,divide, modulusaddition, subtraction<< >>left shift, right shif<<=>>=comparisons== !=equals, not equals&bitwise ANDˆbitwise XOR|bitwise OR&&logical AND, shortcircui||logical OR, shortcircui?:in-line conditionaassignment operators Insidelet,((...)),and$((...)),variable names do not needa$to get their values. ARITHMETIC EVALUATIO$(command)new form`command`old form Runcommand,substitute the results as arguments.Trailing newlines are removed. Characters in$IFS  separate words (see
Field Splitting). Thenew form ispreferred for simpler quoting rules.$((
expression))arithmetic substitutionTheexpressionis evaluated, and the result is used as anargument to the current command.COMMAND SUBSTITUTIOcmd<(list1)>(list2) Runslist1andlist2asynchronously,withstdinand stdoutrespectively connected via pipes using fifos or  files in/dev/fd.These file names become arguments tocmd,which expects to read its first argument and write its second. This only works if you have/dev/fdor fifos. PROCESS SUBSTITUTIOQuoted text becomes one word.Otherwise,occurrences of any character in$IFSseparate words. Multiple whitespace characters that are in$IFSdo not delimit empty words, while multiple non-whitespacecharacters do.When$IFSis not the default value, sequences of leading and trailing$IFSwhitespacecharacters are removed, and printable characters in$IFSsurrounded by adjacent$IFSwhitespacecharacters delimit fields.If$IFSis NULL,bashdoes not do field splitting. FIELDSPLITTING8
chars]match any ofchars(pair separated by amatches a range)[!chars]match any exceptcharschars]match any exceptchars If theextgloboption toshoptis set, the followinextended matching facilities may be used.?(pat-list)optionally match any of the patterns*(pat-list)match 0 or more of any of the patterns+(pat-list)match 1 or more of any of the patterns@(pat-list)match exactly 1 of any of the patterns!(pat-list)match anything but any of the patterns pat-listis a list of one or more patterns separated by|.The POSIX[[=c=]]and[[.c.]]notations for same-weighcharacters and collating elements are accepted.The notation[[:class:]]defines character classes:alnumalphanumericlowerlower-casealphaalphabeticprintprintable blankspace or tabpunctpunctuationcntrlcontrolspacewhitespacedigitdecimalupperupper-casegraphnon-spacesxdigithexadecimaThreeshoptoptions affect pattern matching.dotglobinclude files whose names begin with. nocaseglobignore case when matching  nullglobremove patterns that don’t matchWhen expanding filenames,.and..are ignored, filenames matching the patterns in$GLOBIGNOREarealso ignored and a leading.must be supplied in the pattern to match filenames that begin with..However,settingGLOBIGNOREenables thedotgloboption. Include.*inGLOBIGNOREto get the defaul behavior. PATTERNS Variable names are made up of letters, digits andunderscores. Theymay not startwith a digit. There is no limit on the length of a variable name, and the caseof letters is significant.VARIABLE NAME Assignments to integer variables undergoarithmeticevaluation. Variable assignments have one of the following forms. name=wordsetnametoword name[index]=word set elementindexof arraynametoword name=(word...) set indexed arraynametowords name=( [num]=word...) set given indices of arraynametowordsVARIABLEASSIGNMENT 9$nuse positional parametern,n9${n}use positional parametern$*all positional parameters$@all positional parameters"$*"equivalent to"$1 $2...""$@"equivalent to"$1" "$2"...$#number of positional parametersoptions to shell or byset $?value returned by last command$$process number of current shel$!process number of last backgroundcmd$_name of program in environment a startup.Value of last positional argument in last command.Name of changed mail file in$MAILPATH$auto_resumeenables use of single-wordcommands to match stopped jobs for  foregrounding. With a value ofexact,the word must exactly match thecommand used to startthe job.Withavalue ofsubstring,the typed wordcan be a substring of the command, like%?strin$BASHfull file name used to invokebash$BASH_ENVin normal non-interactive shells only,value is variable, command andarithmetic substituted for path of  startupfile (See
Invocation AndStar tup)$BASH_VERSIONthe version ofbash$BASH_VERSINFO[0]the major version numbe(release)$BASH_VERSINFO[1]the minor version number (version)$BASH_VERSINFO[2]the patchlevel$BASH_VERSINFO[3]the build version$BASH_VERSINFO[4]the release status$BASH_VERSINFO[5]same as$MACHTYPE$CDPATHsearch path forcdcommand$DIRSTACK[*]array variable containing thepushdandpopddirectory stack$ENVin interactive POSIX mode shells, owhen invoked assh,value is variable,command and arithmetic substitutedfor path of startup file$EUIDthe effective user id (readonly)$FCEDITdefault editor for thefccommand (nodefault value)$FIGNOREcolon-separated list of suffixes givingthe set of filenames to ignore whendoing filename completion usingreadline$GLOBIGNOREcolon-separated list of patterns givingthe set of filenames to ignore whendoing pattern matching$GROUPS[*]readonly array variable with the listof groups the user belongs to$histcharscharacters that controlcsh-stylehistory (default:!ˆ#). SeeHistor ySubstitutionPRE-DEFINED VARIABLES10$HISTCMDhistory number o the currentcommand$HISTCONTROLwith a value ofignorespace,donotenter lines that begin with spacesinto the history file.With a value ofignoredups,donot enter a line thatmatches the previous line.Useignorebothto combine both options$HISTFILEwhere command history is stored$HISTFILESIZEmaximum number o lines to keep in$HISTFILE$HISTIGNOREcolon-separated list of patterns; if thecurrent line matches any of them, theline is not entered in the history file.&represents the last history line.Patterns must match the whole line$HISTSIZEnumber of previous commands tokeep available whilebashis running$HOMEhome directory forcdcommand andvalue used for tilde expansion$HOSTFILEfile in format of/etc/hoststo use fohostname completion$HOSTNAMEname of the current host$HOSTTYPEstring describing the current host$IFSfield separators (space,tab,newline)$IGNOREEOFfor interactive shells, the number ofconsecutive EOFs that must beentered beforebashactually exits$INPUTRCname ofreadlinestartupfile,overrides˜/.inputrc$LANGname of current locale$LC_ALLcurrent locale; overrides$LANGandother$LC_variables$LC_COLLATEcurrent locale for character collation,includes sorting results of filenameexpansion$LC_CTYPEcurrent locale for character classfunctions (seePatter ns)$LC_MESSAGEScurrent locale for translating$"..."strings$LINENOline number of line being executed inscript or function$MACHTYPEastring in GNU
cpu-company-system format describing the machine runningbash$MAILname of a mail file, if an$MAILCHECKcheck for mail everynseconds (60default)$MAILPATHfilenames to check for new mail; uses:separator;filenamemay be followed by?message;$_inmessageis matched mail file name.Overrides$MAIL$OLDPWDprevious working directory $OPTARGvalue of last argument processed bgetopts$OPTERRif set to 1, display error messages fromgetopts(default:1)$OPTINDindex of last argument processed bgetopts PRE-DEFINED VARIABLES (continued)11$OSTYPEstring describing theoperating system running  bash$PATHcommand search path$PIPESTATUS[*]array variable containing exit  status values from processes in the most recently executed foreground pipeline$PPIDprocess id of shellsparen$PROMPT_COMMANDcommand to run before each primary prompt $PS1primary prompt strin()$PS2secondary prompt string (>)$PS3selectcommand promp string (#?)$PS4tracing prompt string (+)$PWDcurrent working director$RANDOMset each time itsreferenced,$REPLYset by theselectandreadcommands$SECONDSnumber of seconds since shel invocation$SHELLname of this shel$SHELLOPTScolon-separated list of theenabled shell options forset $SHLVLincremented by one for each sub-bash$TIMEFORMATformat string for output otimekeyword. Special constructs introduced by%.%[p][l]Relapsed secs%[p][l]Uuser CPU secs%[p][l]Ssystem CPU secs%PCPU percentage%%literal%Optionalpgives the precision,the number of digits after thedecimal point; it must be between 0 and 3.Optional produces a longer format, inthe formMMmSS.FFs$TMOUTnumber of seconds to waiduring prompt beforeterminating $UIDthe real user id (readonly) PRE-DEFINED VARIABLE
(continued)Functions run in the same process as the calling script,and share the open files and current directory.Theyaccess their parameters like a script, via$1,$2and soon.$0does not change.returnmay be used inside afunction or.script. Functionsshare traps with theparent script, except forDEBUG.Functions may berecursive, and may have local variables, declared usingdeclare,local,ortypeset.Functions may be exportedinto the environment with.FUNCTIONS12

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->