0% found this document useful (0 votes)
189 views23 pages

Unix Shells Bash Fish KSH TCSH Zsh-Hyperpolyglot

This document summarizes key features of several Unix shell languages including Bash, Fish, Ksh, Tcsh, and Zsh. It covers their grammars and syntax for simple commands, pipelines, lists, grouping, subshells, quoting and escaping, variables, arithmetic expressions, arrays, functions, redirection, job control, and configuration via startup files. The shells allow running commands, setting variables, arithmetic, conditionals, redirection, and background jobs via pipelines and lists along with customization of prompts, key bindings and autoloading of functions.

Uploaded by

sanketdange2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
189 views23 pages

Unix Shells Bash Fish KSH TCSH Zsh-Hyperpolyglot

This document summarizes key features of several Unix shell languages including Bash, Fish, Ksh, Tcsh, and Zsh. It covers their grammars and syntax for simple commands, pipelines, lists, grouping, subshells, quoting and escaping, variables, arithmetic expressions, arrays, functions, redirection, job control, and configuration via startup files. The shells allow running commands, setting variables, arithmetic, conditionals, redirection, and background jobs via pipelines and lists along with customization of prompts, key bindings and autoloading of functions.

Uploaded by

sanketdange2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Hyperpolyglot

UnixShells:Bash,Fish,Ksh,Tcsh,Zsh
grammar|quotingandescaping|characters
variables|variableexpansion|brace,tilde,command,andpathnameexpansion|specialvariables
arithmeticandconditionalexpressions
arrays|associativearrays
functions|commandresolution|argumentsandoptions
executioncontrol
redirection|echoandread|filesanddirectories
processandjobcontrol
history|keybindings
startupfiles|promptcustomization|autoload

Grammar
bash fish ksh tcsh zsh
simplecommand ls ls ls ls ls
simplecommandwithargument echohi echohi echohi echohi echohi
simplecommandwithredirect ls>/tmp/ls.out ls>/tmp/ls.out ls>/tmp/ls.out ls>/tmp/ls.out ls>/tmp/ls.out
simplecommandwithenvironment EDITOR=vigit envEDITOR=vigit EDITOR=vigit envEDITOR=vigit EDITOR=vigit
variable commit commit commit commit commit
pipeline ls|wc ls|wc ls|wc ls|wc ls|wc
sublistseparators &&|| none &&|| &&|| &&||
listterminators ;& ;& ;& ;& ;&
begin;ls;ls;end|
groupcommand {ls;ls;}|wc {ls;ls;}|wc none {ls;ls;}|wc
wc
fishc'ls;ls'|
subshell (ls;ls)|wc (ls;ls)|wc (ls;ls)|wc (ls;ls)|wc
wc

Shellsreadinputuptoanunquotednewlineandthenexecuteit.Anunquotedbackslashfollowedbyanewlineare
discardedandcausetheshelltowaitformoreinput.Thebackslashandnewlinearediscardedbeforetheshelltokenizes
thestring,solonglinescanbesplitanywhereoutsideofsinglequotes,eveninthemiddleofcommandnamesand
variablenames.

Intheshellgrammar,listscontainsublists,whichcontainpipelines,whichcontainsimplecommands.

Subshellsandgroupingcanbeusedtoputalistinapipeline.Subshellsandgroupscanhavenewlines,buttheshell
defersexecutionuntiltheendofthesubshellorgroupisreached.

Thesectiononexecutioncontroldescribesstructureswhichdonotfitintothesimplegrammarandexecutionmodel
outlinedhere.Theshellwillnotexecuteanyofthecontrolstructuresuntiltheendkeywordisreached.Asaresult,the
controlstructurecancontainmultiplestatementsseparatedbynewlines.Executioncontrolstructurescannotbeputinto
pipelines.

simplecommand
Initssimplestformalineinashellscriptisaworddenotingacommand.Theshelllookssuccessivelyforauser
definedfunction,builtinfunction,andexternalcommandinthesearchpathmatchingtheword.Thefirstonefoundis
run.Ifnomatchingfunctionorexternalcommandisfoundtheshellemitsawarningandsetsitsstatusvariabletoa
nonzerovalue.Itdoesnotreturnthestatusvaluetoitscallerunlessithasreachedtheendofitsinput,however.

tcsh lacksuserdefinedfunctionsbutbuiltinsstilltakeprecedenceoverexternalcommands.

simplecommandwithargument
Commandscanbefollowedbyoneormorewordswhicharetheargumentstothecommand.Howashelltokenizesthe
inputintowordsiscomplicatedinthegeneralcase,butinthecommoncasetheargumentsarewhitespacedelimited.

simplecommandwithredirect
Thestandardoutput,standardinput,andstandarderrorofthecommandcanberedirectedtofiles.Thisisdescribed
underredirection.

simplecommandwithenvironmentvariable
Anonceenvironmentvariablecanbesetfortheexclusiveuseofthecommand.

pipeline
Pipelinesareasequenceofsimplecommandsinwhichthestandardoutputofeachcommandisredirectedtothe
standardinputofitssuccessor.

Apipelineissuccessfulifthelastcommandreturnsazerostatus.

sublistseparators
Sublistisatermfromthe zsh documentationdescribingoneormorepipelinesseparatedbytheshortcutoperators &&
and || .When && isencountered,theshellstopsexecutingthepipelinesifthepreviouspipelinefailed.When || is
encountered,theshellstopsexecutingifthepreviouspipelinesucceeded.Asublistissuccessfulifthelastcommandto
executereturnsazerostatus.

fish:

Fishhasshortcircuitoperatorsthefollowingareequivalentto ls&&ls and ls||ls :


$ls;andls
$ls;orls

listterminators
Alistisasequenceofsublistsseparatedbysemicolons orampersands & andoptionallyterminatedbyasemicolon
orampersand.

Iftheseparatororterminatorisanampersand,theprevioussublistisruninthebackground.Thispermitstheshellto
executethenextsublistorthesubsequentstatementwithoutwaitingfortheprevioussublisttofinish.

groupcommand
Agroupcommandcanbeusedtoconcatenatethestdoutofmultiplecommandsandpipeittoasubsequentcommand.

Ifthegrouphasaninputstream,itisconsumedbythefirstcommandtoreadfromstdin.

bash requiresthatthefinalcommandbeterminatedbyasemicolon zsh doesnot.

subshell
Likethegroupcommand,butthecommandsareexecutedinasubshell.Variableassignmentsorchangeofworking
directoryarelocaltothesubshell.

QuotingandEscaping
bash fish ksh tcsh zsh
allows\'and\\escapes:
literalquotes 'foo' 'foo' 'foo' 'foo'
'foo'
setfoo7
setenv
"foois$foo"
foo=7 foo=7 foo7 foo=7
interpolatingquotes
"foois$foo" "foois$foo" "foois "foois$foo"
doublequotesdonotperform
$foo"
commandsubstitution
interpolatingquotesescape
\$\\\`\" \"\$\\ \$\\\` none \$\\\`\"
sequences
quoteswithbackslash
$'foo\n' none $'foo' none $'foo'
escapes
\a\b\e\E\f\n \a\b\e\E\f\n \a\b\e\E\f\n
\r\t\v \r\t\v \r\t\v
quotedbackslashescapes none none
\\\'\"\ooo\xhh \\\'\"\ooo\xhh \\\'\"\ooo\xhh
\cctrl \cctrl \cctrl
\a\b\e\f\n\r\t\v
\space
\$\\\*\?\~\%\#\(\)\
unquotedbackslash {
\space \space \space \space
escapes \}\[\]\<\>\^\&\;\"
\'
\xhh\Xhh\ooo\uhhhh
\Uhhhhhhhh\cctrl
$(ls) $(ls) $(ls)
commandsubstitution (ls) `ls`
`ls` `ls` `ls`
\$\\
backtickescapesequences \$\\\`\newline none \$\\\`\newline \$\\\`\newline
\newline

literalquotes
Literalquotes(akasinglequotes)createawordwithexactlythecharactersshowninthesourcecode.Fortheshells
otherthan fish thereisnoescapingmechanismandhencenowaytoputsinglequotesintheword.

Literalquotescanbeusedtoputcharactersthattheshelllexerusestodistinguishwordsinsideasingleword.For
bash thesecharactersare:

|&;()<>spacetab

Literalsquotescanalsobeusedtopreventtheparameter,brace,pathname,andtildeexpansionaswellascommand
substitution.For bash thespecialcharactersthattriggertheseexpansionsare:

${}*?[]`~

interpolatingquotes
Interpolatingquotes(akadoublequotes)performparameterexpansionandcommandsubstitutionofboththe$()and``
variety.Theydonotperformbrace,pathname,ortildeexpansion.$and`arethusspecialcharactersbuttheycanbe
escapedwithabackslashascanthebackslashitself,thedoublequote,andanewline.

interpolatingquotesescapesequences
Theescapesequencesavailableininterpolatingquotes.

quoteswithbackslashescapes
StringliteralswhichsupportCstyleescapes.
quotedbackslashescapes
TheCstylestringliteralescapes.

unquotedbackslashescapes
fish permitstheuseofCescapesoutsideofquotes.

commandsubstitution
Howtoexecuteacommandandgettheoutputasshelltext.

Ifthecommandoutputcontainswhitespace,theshellmayparsetheoutputintomultiplewords.Doublequotescanbe
usedtoguaranteethatthecommandoutputistreatedasasinglewordbytheshell:

"$(ls)"
"`ls`"

backtickescapesequences
Escapesequencesthatcanbeusedinsidebacktickquotes.

Characters
bash fish ksh tcsh zsh
word |&;()<>SPHT |&;()<>SPHT |&;()<>SPHT |&;()<>SPHT
|&;()<>SPHTLF
separating LF LF LF LF
quotingand
"'\ "'\ "'\ "'\ "'\
escaping
variable:$ variable:$ variable:$
variable:$ variable:$
brace:{} brace:{} brace:{}
brace:{} brace:{}
shell tilde:~ tilde:~ tilde:~
tilde:~ tilde:~
expansion command:` command:` command:`
command:() command:`
pathname:*?[] pathname:*?[] pathname:*?[]
pathname:*? pathname:*?[]
history:!^ history:!^ history:!^
otherspecial #= #[] #=. # #=
AZaz09_., AZaz09_.,:+ AZaz09_,:+ AZaz09_.,: AZaz09_.,
bareword
:+/@% /@%!^= /@%!^ +/@%= :+/@%
variablename AZaz09_ AZaz09_ AZaz09_ AZaz09_ AZaz09_

wordseparating
Theshelltokenizesitsinputintowords.Characterswhicharenotwordseparatinganddonothaveanywordseparating
charactersbetweenthemarepartofthesameword.

quotingandescaping
Fortwocharacterstobeindifferentwords,thepresenceofawordseparatingcharacterbetweenthemisnecessarybut
notsufficient,becausetheseparatingcharactermustnotbequotedorescaped.

Thefollowingtwolinesbothtokenizeasasingleword:

"loremipsum"
lorem""ispum

shellexpansion
Thepresenceofshellexpansioncharactersinawordcausestheshelltoperformatransformationontheword.The
transformationmayreplacethewordwithmorethanoneword.

Inthefollowingexample,theword *.c willbereplacedbymultiplewordsifthereismorethanonefilewitha .c suffix


intheworkingdirectory:

grepmain*.c

Squarebrackets [] areusedforbothpathnameexpansion,wherethebracketscontainalistofcharacters,andarray
notation,wherethebracketscontainanindex.Webelievethatincasesofambiguity,thesyntaxisalwaystreatedas
arraynotation. fish doesnothavethisambiguitybecauseitdoesnotusesquarebracketsinpathnameexpansion.

zsh:

In zsh variableexpansionwillexpandtoasingleword,evenifthevariablecontainswordseparatingcharacters.This
behaviorisdifferentfromtheothershells.

Avariablecanbeexpandedtomultiplewordswiththe ${=VAR } syntax,however.

$functioncountem(){echo$#;}

$foo='onetwothree'

$countem$foo
1

$countem${=foo}
3

otherspecialcharacters
comments:

Thenumbersign # canbeusedtostartacommentwhichendsattheendoftheline.The # mustbebyitselforthe


firstcharacterinaword.

In tcsh ,commentsarenotsupportedwhentheshellisinteractive.

In zsh ,commentsarenotsupportedbydefaultwhentheshellisinteractive.Thiscanbechangedbyinvoking zsh with


the k flagorbyrunning:

setoINTERACTIVE_COMMENTS

variableassignment:

Theequalssign = isusedforvariableassignmentin bash , ksh ,and zsh .Giventhatspacescannotbeplacedaround


theequalssign,itseemslikelythetokenizertreatsitlikeotherbarewordcharacters.Notethatinasimplecommand,the
commandnameisthefirstwordwhichdoesnotcontainanequalssign.

namespaces:

ksh hasnamespaces.Theycanbeusedforvariablenamesandfunctionnames:

$bar=3

$namespacefoo{bar=4;}

$echo$bar
3

$namespacefoo{echo$bar;}
4

$echo${.foo.bar}
4

barewordcharacters
Abarewordisawordwhichisnotquotedanddoesnotcontainescapes.Thecharacterswhicharelistedaboveare
thosewhichcanappearanywhereinabareword.

Someoftheothercharacterscanappearinbarewordsundercertaincircumstances.Forexamplethetilde ~ canappear
ifitisnotthefirstcharacter.

variablenamecharacters
Characterswhichcanbeusedinvariablenames.

Notethatavariablenamecannotstartwithadigit.Also, $_ isaspecialvariablewhichcontainsthepreviouscommand.

Variables
bash fish ksh tcsh zsh external
var=val setgvarval var=val setvar=val var=val
globalvariables $var $var $var $var $var
set setg set set set
set,get,list,unset,edit unsetvvar setevar unsetvvar unsetvar unsetvvar
none varedvar none none varedvar
readonlyvariables readonlyvar readonlyvar readonlyvar
readonly readonly readonly
none none
markreadonly,setandmarkreadonly,list var=val var=val var=val
readonly readonlyp readonlyp readonlyp
setgxvar
setenvvar
$var
exportedvariables exportvar exportvar $var exportvar none
setgxvar
exportvar=val exportvar=val setenvvar exportvar=val none
val
export,setandexport,listexported,undo exportp exportp val exportp printenv
setx
export exportnvar none printenv none none
setguvar
none
$var
options setoopt setoopt setoopt
seto none seto none seto
set,list,unset set+oopt set+oopt set+oopt
declare
functions
setopt
othervariablebuiltins declare @
float
integer
unsetopt

globalvariables
Howtosetaglobalvariablehowtogetthevalueofaglobalvariablehowtolistalltheglobalvariableshowtounseta
globalvariablehowtoeditavariable.
Variablesareglobalbydefault.

In tcsh ifvarisundefinedthenencountering$varthrowsanerror.Theothershellswilltreat$varasanemptystring.

Ifthereisavariablenamed foo ,then

unsetfoo

willunsetthevariable.However,ifthereisnosuchvariablebutthereisafunctionnamed foo ,thenthefunctionwillbe


unset. unsetv willonlyunsetavariable.

readonlyvariables
Howtomarkavariableasreadonlyhowtosimultaneouslysetandmarkavariableasreadonlyhowtolisttheread
onlyvariables.

Anerrorresultsifanattemptismadetomodifyareadonlyvariable.

exportedvariables
Howtoexportavariablehowtosetandexportavariablehowtolisttheexportedvariables.

Exportedvariablesarepassedtochildprocessesforkedbytheshell.Thiscanbepreventedbylaunchingthe
subprocesswith envi .Subshellscreatedwithparens()haveaccessnonexportedvariables.

The tcsh exampleforexportingavariablewithoutsettingitisn'tthesameasthecorrespondingexamplesfromthe


othershellsbecausein tcsh anerrorwillresultifthevariableisn'talreadyset.

options
Optionsarevariableswhicharenormallysetviaflagsatthecommandlineandaffectshellbehavior.

VariableExpansion
bash fish ksh tcsh zsh external
setgvar setenv
setvariablevalue var=val var=val var=val
val varval
getvariablevalue $var $var $var $var $var
concatenatevariable
${var}val {$var}val ${var}val ${var}val ${var}val
andvalue
coalesce ${var:val} ${var:val} ${var:val}
coalesceandassignif
${var:=val} ${var:=val} ${var:=val}
null
messagetostderrand
${var:?msg} ${var:?msg} ${var:?msg}
exitifnull
offsetisonebased;
offsetiszero offsetiszero offsetiszero
wheninputlacks
based: based: based:
substring newlines:
${var:offset} ${var:offset} ${var:offset}
awk'{printsubstr($0,
${var:offset:len} ${var:offset:len} ${var:offset:len}
offset,len)}'
length ${#var} ${#var} ${%var} ${#var} wcm
foo=do.re.mi foo=do.re.mi foo=do.re.mi
removeprefixgreedily sed's/^.*\.'
${foo##*.} ${foo##*.} ${foo##*.}
foo=do.re.mi foo=do.re.mi foo=do.re.mi
removeprefixreluctantly sed's/^[^\.]*\.'
${foo#*.} ${foo#*.} ${foo#*.}
foo=do.re.mi foo=do.re.mi foo=do.re.mi
removesuffixgreedily sed's/\..*$'
${foo%%.*} ${foo%%.*} ${foo%%.*}
foo=do.re.mi foo=do.re.mi foo=do.re.mi
removesuffixreluctantly sed's/\.[^\.]*$'
${foo%.*} ${foo%.*} ${foo%.*}
foo='doremimi' foo='doremimi' foo='doremimi'
singlesubstitution sed's/mi/ma/'
${foo/mi/ma} ${foo/mi/ma} ${foo/mi/ma}
foo='doremimi' foo='doremimi' foo='doremimi'
globalsubstitution sed's/mi/ma/g'
${foo//mi/ma} ${foo//mi/ma} ${foo//mi/ma}
foo=txt.txt foo=txt.txt foo=txt.txt
prefixsubstitution sed's/^txt/text/'
${foo/#txt/text} ${foo/#txt/text} ${foo/#txt/text}
foo=txt.txt foo=txt.txt foo=txt.txt
suffixsubstitution sed's/txt$/html/'
${foo/%txt/html} ${foo/%txt/html} ${foo/%txt/html}
foo=lorem foo=lorem tr'[:lower:]'
uppercase none
${foo^^} ${foo:u} '[:upper:]'
foo=lorem
uppercasefirstletter none none
${foo^}
foo=LOREM foo=LOREM tr'[:upper:]'
lowercase none
${foo,,} ${foo:l} '[:lower:]'
foo=LOREM
lowercasefirstletter none none
${foo,}
foo=~
absolutepath
${foo:a}
foo=/etc/hosts foo=/etc/hosts
dirname
${foo:h} dirname$foo
foo=/etc/hosts foo=/etc/hosts
basename
${foo:t} basename$foo
foo=index.html
extension
${foo:e}
foo=index.html
root
${foo:r}

Brace,Tilde,Command,andPathnameExpansion
bash fish ksh tcsh zsh
braceexpansion:list echo{foo,bar} echo{foo,bar} echo{foo,bar} echo{foo,bar} echo{foo,bar}
braceexpansion:sequence echo{1..10} none echo{1..10} none echo{1..10}
braceexpansion:charactersequence echo{a..z} none echo{a..z} none none
tildeexpansion echo~/bin echo~/bin echo~/bin echo~/bin echo~/bin
commandexpansion:dollarparens echo$(ls) echo(ls) echo$(ls) none echo$(ls)
commandexpansion:backticks echo`ls` none echo`ls` echo`ls` echo`ls`
processsubstitution wc<(ls) wc(ls|psub) wc<(ls) none wc<(ls)
pathexpansion:string echo/bin/c* echo/bin/c* echo/bin/c* echo/bin/c* echo/bin/c*
pathexpansion:character echo/bin/c?? echo/bin/c?? echo/bin/c?? echo/bin/c?? echo/bin/c??
pathexpansion:characterset echo/bin/[cde]* none echo/bin/[cde]* echo/bin/[cde]* echo/bin/[cde]*
pathexpansion:negatedcharacterset echo/bin/[^cde]* none echo/bin/[^cde]* echo/bin/[^cde]* echo/bin/[^cde]*
pathexpansion:sequenceofcharacters echo/bin/[af]* none echo/bin/[af]* echo/bin/[af]* echo/bin/[af]*

SpecialVariables
inzshterminology,specialmeansreadonlyvariablesthatcannothavetheirtypechanged

nonalphabeticalvariables
bash fish ksh tcsh zsh
nameofshellorshellscript $0 (statusf) $0 $0 $0
$1,$2,
commandlinearguments $1,$2, $argv[1],$argv[2], $1,$2, $1,$2,
$argv[1],$argv[2],
$#
numberofcommandlineargs $# (count$argv) $# $#
$#argv
$* $* $*
arguments$1,$2, none $*
$@ $@ $@
"$1""$2""$3" "$@" $argv "$@" "$@"
"$1c$2c$3"wherecisfirstcharacterof$IFS "$*" "$argv" "$*" "$*"
processid $$ %self $$ $$ $$
processidoflastasynchronouscommand $! none $! $! $!
exitstatusoflastnonasynchronouscommand $? $status $? $? $?
currentcommandexecuting:
previouscommandexecuted $_ $_ $_ $_
$_
commandlineoptions $ none $ none $
readinput none none none $< none

$*and$@
Theseparametersbehavedifferentlyindoublequotes.

Normallyyoushoulduse"$@"topassalltheparameterstoasubcommand.Thesubcommandwillreceivethesame
numberofparametersasthecallerreceived.

"$*"canbeusedtocollecttheparametersinastring.Thefirstcharacterof$IFSisusedasthejoinseparator.This
couldbeusedtopassalloftheparametersasasingleparametertothesubcommand.

Outsideofdoublequotes,$*[email protected],however.In
bash ifyouusethemtopassparameterstoasubcommand,thesubcommandwillreceivemoreparametersthanthe
callerifanyoftheparameterscontainwhitespace.

In zsh $*and$@behavelike"$@".

setbyshell
bash fish ksh tcsh zsh
shellversion BASH_VERSION KSH_VERSION tcsh ZSH_VERSION
returnvalueoflastsyscall ERRNO
history history
currentlinenumberofscript LINENO LINENO LINENO
OPTARG OPTARG OPTARG
setbygetopts
OPTIND OPTIND OPTIND
OSTYPE
operatingsystemandmachinetype
MACHTYPE
shellparentpid PPID PPID PPID
PWD PWD PWD PWD
workingdirectoryandpreviousworkingdirectory
OLDPWD none OLDPWD OLDPWD
builtinfunction:
randominteger RANDOM RANDOM RANDOM
random
returnvalue REPLY REPLY REPLY
secondssinceshellwasinvoked SECONDS SECONDS SECONDS
incrementedeachtimeasubshelliscalled SHLVL SHLVL
readbyshell
bash fish ksh tcsh zsh
browser BROWSER
CDPATH
cdsearchpath CDPATH CDPATH CDPATH cdpath
cdpath
COLUMNS COLUMNS
terminalwidthandheight
LINES LINES
FCEDIT FCEDIT FCEDIT
commandhistoryeditor
EDITOR EDITOR EDITOR
shellstartupfile ENV ENV ENV
fpath
functiondefinitionsearchpath FPATH
FPATH
historyfilepath HISTFILE HISTFILE HISTFILE
sizeofhistory HISTSIZE HISTSIZE HISTSIZE
homedirectory HOME HOME HOME HOME
inputfieldseparators IFS IFS IFS
locale LANG LANG LANG
NULLCMD
nullredirectcommand
READNULLCMD
commandsearchpath PATH PATH PATH PATH
promptcustomization
PS1PS2PS4 PS1PS2PS3PS4 PS1PS2PS3PS4
main,secondary,select,trace
rightpromptcustomization RPS1RPS2
terminaltype TERM TERM
timeout TMOUT TMOUT
systemtmpdirectory TMPDIR
user USER

ArithmeticandConditionalExpressions
bash fish ksh tcsh zsh
[e/etc] [e/etc] [e/etc] [e/etc]
testcommand
teste/etc teste/etc teste/etc teste/etc
truecommand true true true true
falsecommand false false false false
conditionalcommand [[]] [[]] [[]]
conditionalexpression ()
arithmeticexpansion $((1+1)) math'1+1' $((1+1)) $((1+1))
floatingpointexpansion none math'1.1+1.1' $((1.1+1.1)) $((1.1+1.1))
letexpression let"var=expr" let"var=expr" let"var=expr"
expr1+1 expr1+1 expr1+1 expr1+1 expr1+1
externalexpression
expr0'<'1 expr0'<'1 expr0'<'1 expr0'<'1 expr0'<'1
arithmeticcommand (()) (()) (())
whiletrue;do whiletrue whiletrue;do while(1) whiletrue;do
readp'$'cmd readcmd readcmd?'$' echon'%' readcmd\?'$'
eval
eval$cmd eval$cmd eval$cmd eval$< eval$cmd
done end done end done
filetest

Expressionsareimplementedaseithercommandexpressionswhichreturnanintegerstatuslikeacommand,orvariable
expressionswhichevaluatetoastring.Commandexpressionsreturnastatusof0fortrueandanonzerostatusfor
false.Onlycommandsandcommandexpressionscanbeusedastheconditionalinif,while,anduntilstatements.

Expressionswhichsupportarithmeticonlysupportintegerarithmetic.

[] [[]] $(()) (()) () expr math


conditional arithmetic arithmetic conditional
name testcommand externalexpression
command expansion command expression
tcsh fish
usedas command command argument command command
conditionals expressions
wordsplitting? yes no
expansions
anythingbut anythingbut
true 1 1 1 anythingbut''or0
'' ''
falsehoods '' '' 0 0 0'' 0''
logicaloperators ao! &&||! &&||! &&||! &&||! &|none
regexcomparison
none =~ none none str:regex
operator
=>>=<<=!=
stringcomparison
=!= ==!= none none ==!= butcomparisonisnumericif
operators
operandsaredigits
arithmetic
eqnelt eqnelt ==!=<> ==!=<> ==!=<><=
comparison =>>=<<=!=
gtlege gtlege <=>= <=>= >=
operators
arithmetic +*/% +*/%
none none +*/% +*/%
operators ** **
usecmdsubstitution,ie.
grouping \(\) 2*(3+4) forbash:

expr2\*$(expr3+4)
$((n=7 ((n=7
assignment none none )) ))
echo$n echo$n
+==*=/= +==*=
compound
none none %= /=%=
assignment
andothers andothers
$((n=7, ((n=7,
commaand
none none n++)) n++))
increment
echo$n echo$n
<<>>&|^ <<>>&| <<>>&|^
bitoperators none none
~ ^~ ~
eEXISTS?
dDIR?
f
REGULAR_FILE?
(h|L)
SYMLINK?
p
filetests
NAMED_PIPE?
rREADABLE?
sNOT_EMPTY?
wWRITABLE?
x
EXECUTABLE?
SSOCKET?

name
Thenameoftheexpression.

testcommand
conditionalcommand
conditionalexpression

arithmeticexpansion
letexpression
externalexpression

arithmeticcommand
Anarithmeticcommandcanbeusedtotestwhetheranarithmeticexpressioniszero.

Supportsthesametypeofexpressionsas $(()) .

truecommand
Anoopcommandwithanexitstatusof0.Oneapplicationistocreateaninfiniteloop:

whiletrue;do
echo"Arewethereyet?"
done

falsecommand
Anoopcommandwithanexitstatusof1.Oneapplicationistocommentoutcode:

iffalse;then
start_thermonuclear_war
fi

eval
Howtoevaluateastringasashellcommand.

Arrays
bash fish ksh tcsh zsh
declare typesetavar none none none typesetavar
listallarrays typeseta none none none typeseta
literal a=(doremi) setadoremi a=(doremi) seta=(doremi) a=(doremi)
${a[1]}
lookup ${a[0]} $a[1] ${a[0]} ${a[1]}
$a[1]
returnslast returnslast
negativeindex returnslastelement: returnslastelement:
element: none element:
lookup ${a[1]} ${a[1]}
$a[1] ${a[1]}
slice ${a[@]:2:3} $a[(seq23)] ${a[@]:1:2} ${a[23]} $a[2,3]
${a[*]:2:3} ${a[*]:1:2}
a[0]=do seta[1]do a[0]=do seta[1]=do a[1]=do
update a[1]=re seta[2]re a[1]=re seta[2]=re a[2]=re
a[2]=mi seta[3]mi a[2]=mi seta[3]=mi a[3]=mi
errormessageand lookupreturns
lookupreturnsempty nonzeroexitstatus lookupreturnsempty emptystring
lookupandupdate
string string
outofbounds bothproduce
updateexpands updateexpands
behavior errormessageand
updateexpandsarray; array;inbetween updateexpandsarray; array;inbetween
nonzeroexitstatus
arraycanhavegaps slotsgetempty arraycanhavegaps slotsgetempty
strings strings
highestindex: highestindex: ${#a}
size ${#a[@]} count$a ${#a[@]} ${#a} ${#a[@]}
${#a[*]} ${#a[*]} ${#a[*]}
cancontaingaps: cancontaingaps:
listindices ${!a[@]} (seq(count$a)) ${!a[@]} `seq${#a}` $(seq${#a})
${!a[*]} ${!a[*]}
returnallelements returnallelements returnallelements
regularreference returnfirstelement returnfirstelement
joinedbyspace joinedbyspace joinedbyspace
regular assignsto0indexed convertarrayto assignsto0indexed convertarrayto convertarrayto
assignment slot regularvariable slot regularvariable regularvariable
setea[1]
deleteelement unseta[0] a[0]=()
reisnowatindex1
unseta[@]
deletearray setea unsetva
unseta[*]
passeach
elementas cmd"${a[@]}" cmd$a cmd"${a[@]}" cmd"${a[@]}"
argument
passassingle
cmd"${a[*]}" cmd"$a" cmd"${a[*]}" cmd"${a[*]}"
argument

Shellarraysarearraysofstrings.Inparticulararrayscannotbenested.

Arrayswithoneelementareforthemostpartindistinguishablefromavariablecontaininganonemptystring.Empty
arraysareforthemostpartindistinguishablefromavariablecontaininganemptystring.

Inthecaseof bash or zsh ,itispossibletotellwhetherthevariableisanarraybyseeingwhetheritislistedinthe


outputof typeseta .

declare
bash and zsh allowonetodeclareanarray.Thiscreatesanemptyarray.Theredoesn'tappeartobeanyneedtodo
this,however,

listallarrays

literal
bash and zsh usparenstodelimitanarrayliteral.Spacesseparatetheelements.Iftheelementsthemselvescontain
spaces,quotesorbackslashescapingmustbeused.

lookup

update
outofboundsbehavior
size

listindices
regularreference
regularassignment

deletevalue
Deletingelementsfroma bash arrayleavesgaps.Deletingelementsfroma zsh arrayscauseshigherindexed
elementstomovetolowerindexpositions.

deletearray

AssociativeArrays
bash fish ksh tcsh zsh
declare typesetAvar none none none typesetAvar
listallassociativearrays typesetA none none none typesetA
assignvalue foo[bar]=baz none none none foo[bar]=baz
lookup ${foo[bar]} none none none ${foo[bar]}
${!foo[@]}
listindices none none none
${!foo[*]}
deletevalue unset"foo[bar]" none none none unset"foo[bar]"
deletearray unset"var[@]" none none none unsetvfoo

Associativearrayswereaddedto bash withversion4.0.

Functions
bash fish ksh tcsh zsh
foo(){
foo(){ foo(){
definewith echo
echofoo none none echofoo
parens foo
} }
}
function
functionfoo{ functionfoo foo{ functionfoo{
definewith
echofoo echofoo echo none echofoo
keyword
} end foo }
}
functionfood'echofoo'
definewith
echofoo
docstring
end
in.zshrc:
edit autoloadUzed
function funcedfoo
definition ^Jwhendone:
zedffoo
$1,$2,
parameters $1,$2, $argv[1],$argv[2], none $1,$2,

numberof
$# (count$argv) $# none $#
parameters
false()
false(){ functionfalse { false(){
return return1 return1 return none return1
} end 1 }
}
{0,,2**311}
{2**31,,2**311}
negativevaluesresultin
return {0,,
{0,,255} returnvalueof"" none
values 255} otherintegersconvertedtooneofthe
abovevaluesbymodulararithmetic
valuesabove2**311
causeerror
functionfoo
foo(){ setlbar7 foo(){
localbar=7 end localbar=7
local } }
none none
variables withoutthelflag,the
variablessetwithoutthe thevariablewill variablessetwithoutthelocalkeyword
localkeywordareglobal beglobalifalready areglobal
defined,otherwiselocal
list
typesetf|grep'()' functions none typesetf|grep'()'
functions
show typeset
typesetffunc functionsfunc typesetffunc
function ffunc
delete unsetf unsetffunc
unsetffunc functionsefunc none
function func unfunctionfoo

definewithparens
Howtodefineafunction.

POSIXcallsforparensinthedeclaration,butparametersarenotdeclaredinsidetheparens,norareparensusedwhen
invokingthefunction.Functionsareinvokedwiththesamesyntaxusedtoinvokeexternalcommands.Defininga
functionhidesabuiltinoranexternalcommandwiththesamename,butthebuiltinorexternalcommandcanstillbe
invokedwiththe builtin or command modifiers.

definewithkeyword
Howtodefineafunctionusingthe function keyword.

definefunctionwithdocstring
editfunctiondefinition

parameters
Thevariableswhichholdthefunctionparameters.

Outsideofafunctionthevariables$1,$2,refertothecommandlineargumentsprovidedtothescript.

$0alwaysrefersthenameofthescriptinanoninteractiveshell.

numberofparameters
Thevariablecontainingthenumberoffunctionparameterswhichwereprovided.

Outsideofafunction$#referstothenumberofcommandlinearguments.
return
Ifafunctiondoesnothaveanexplicit return statementthenthereturnvalueistheexitstatusofthelastcommand
executed.Ifnocommandexecutedthereturnvalueis0.

returnvalues
Shellfunctionscanonlyreturnintegers.Someshellslimitthereturnvaluetoasinglebyte.Thisisalltheinformationone
cangetfromtheexitstatusofanexternalprocessaccordingtothePOSIXstandard.

Ifashellfunctionneedstoreturnadifferenttypeofvalue,itcanwriteittoaglobalvariable.Allvariablesareglobalby
default.Thevalueinoneoftheparameterscanbeusedtodeterminethevariabletowhichthereturnvaluewillbe
written.Considerthisimplementationof setenv :

setenv(){
eval$1=$2
}

localvariables
Howtodeclareandsetalocalvariable.

Localvariablesarenormallydefinedinsideafunction. bash throwsanerrorwhenanattemptismadetodefinealocal


outsideafunction,but dash and zsh donot.

Localvariableshavelexical,notdynamicscope.Ifafunctionrecurses,localsinthecallerwillnotbevisibleinthe
callee.

listfunctions
Howtolisttheuserdefinedfunctions.

typesetf withoutanargumentwillshowallfunctiondefinitions.

bash and zsh alwaysthefunctiondefinitionswiththeparensyntax,evenifthefunctionkeywordsyntaxwasusedto


definethefunction.

showfunction
Howtoshowthedefinitionofafunction.

deletefunction
Howtoremoveauserdefinedfunction.

CommandResolution
bash fish ksh tcsh zsh
aliasll='ls aliasll='ls aliasllls
alias: aliasltr'lsltr' aliasll='lsl'
l' l' l
functions aliasL
alias alias alias
define,list,remove,definesuffix functionseltr unaliasll
unaliasll unaliasll unaliasll
alias none aliasstxt=cat
none none none
builtincmd
builtincmd builtincmd builtincmd none
none
builtins: enablea builltinn none builtins
typecommandname;then
helpcmd cmdhelp none none
Mh
run,list,help,enable,disable enablecmd none none none
enablecmd
enablencmd none none none
disablecmd
runexternalcommand commandcmd commandcmd commandcmd commandcmd
runwithexplicitenvironment envivar=valcmdargs
aliast
hash none hash
aliast
externalcommandhashes: none none hashcmd=path
doesnotcachecommand cmd=path
hashdcmd none unhash
paths none
list,set,deletefrom,clear,rebuild hashr rehash hashr
aliasr
none none hashf
none
commandtype typecmd typecmd typecmd typecmd
commandv commandvcmd
commandpath commandvcmd whencecmd cmd whichcmd
whichcmd whencecmd
wherecmd
commandpaths wherecmd
whichacmd

alias
Aliasexpansionisdoneafterhistoryexpansionandbeforeallotherexpansion.Acommandcanbeexpandedbymultiple
aliases.Forexamplethefollowingwillecho"baz":

aliasbar=echo"baz"
aliasfoo=bar
foo

Ontheotherhandtheshellsseemsmartenoughaboutaliasingtonotbeputintoaninfiniteloop.Thefollowingcode
causesanerror"foonotfound":
aliasfoo=bar
aliasbar=foo
foo

Aliasdefinitionsarenotregistereduntilanentirelineofinputisread.Thefollowingcodecausesanerror"lshomenot
found":

aliaslshome='ls~';lshome

Userdefinedfunctionscanreplacealiasesintheshellswhichhavethemi.e.allshellsexcept tcsh .

TheKornshellhasafeaturecalledtrackedaliaseswhichareidenticaltotheexternalcommandhashesoftheother
shells.

builtins

runexternalcommand
Whenresolvingcommands,userdefinedfunctionstakeprecedenceoverexternalcommands.Ifauserdefinedfunction
ishidinganexternalcommand,the command modifiercanbeusedtorunthelatter.

runwithexplicitenvironment
Howtorunacommandwithanexplicitenvironment. envi clearstheenvironmentofexportedvariablesandonly
providestheexternalcommandwiththeenvironmentvariablesthatareexplicitlyspecified.Ifthe i optionisnot
specifiedthentheenvironmentisnotcleared,whichinmanycasesisnodifferentthanifthecommandhadbeenrun
directlywithoutthe env command.The env commandwithoutthe i optionisusedinshebangscriptstoavoidhard
codingthepathoftheinterpreter.

Multipleenvironmentvariablescanbesetwiththeenvcommand:

enviVAR1=VAL1VAR2=VAL2...CMD

externalcommandhashes
Externalcommandhashesareamappingfromcommandnamestopathsonthefilesystem.

TheKornShellcallsexternalcommandhashes"trackedaliasaes",and ksh defines hash asanaliasfor aliast .

commandtype
Determinewhattypeacommandis.Thepossibletypesarealias,shellfunction,shellbuiltin,orapathtoanexternal
command.Ifthecommandisnotfoundanexitstatusof1isreturned.

commandpath
Returntheabsolutepathforanexternalcommand.Forshellfunctionsandshellbuiltinsthenameofthecommandis
returned.Foraliasesthestatementusedtodefinethealiasisreturned.Ifthecommandisnotfoundanexitstatusof1
isreturned.

commandpaths

ArgumentsandOptions
bash fish ksh tcsh zsh
executecommandand $bashc'echo $fishc'echo $kshc'echo $tcshc'echo
$zshc'echofoo'
exit foo' foo' foo' foo'
usage $bashhelp $fishhelp $tcshhelp $zshhelp
interactiveshell $bashi $fishi $kshi $tcshi $zshi
$bashl $fishl $zshl
loginshell $kshl $tcshl
$bashlogin $fishlogin $zshlogin
makeposixcompliant $bashposix
$bashr $zshr
restrictedmode $kshr
$bashrestricted $zshrestricted
showversion $bashversion $fishversion $tcshversion $zshversion
shiftpositional
parameters: shift shift shift shift
shiftn shiftn none shiftn
byone,byn
setpositionalparameters setarg setarg setarg
getopts getoptsoptsvar getoptsoptsvar getoptsoptsvar

optionscanbesetbythescriptusing set .Also seto (bash)andpipefail.

executecommandandexit
Shellexecutesasinglecommandwhichisprovidedonthecommandlineandthenexits.

usage
Shellprovideslistofoptionsandexits.
interactiveshell
Aninteractiveshellisonethatisnotprovidedascriptwheninvokedasanargumentorisnotinvokedwiththe c
option.The i optionmakesascriptinteractiveregardless.Typicallyaninteractiveshellgetsitsinputfromandsends
itsoutputtoaterminal.AninteractiveshellignoresSIGTERMandwillhandlebutnotexitwhenreceivingaSIGINT.
Interactiveshellsdisplayapromptandenablejobcontrol.Inaninteractiveshelltheoctothorpe#causesasyntaxerror,
unlikeinnoninteractiveshellswhereitistreatedasthestartofacomment.

loginshell
Aloginshellisaspecialtypeofinteractiveshell.Itexecutesdifferentstartupfilesandwillalsoexecuteanylogoutfiles.
WhenitexitsitsendsaSIGHUPtoalljobs.(isthistrue?)Aloginshellignoresthe suspend builtin.

makeposixcompliant
ChangethebehavioroftheshelltobemorePOSIXcompliant.

restrictedmode
Shellrunsinrestrictedmode.

showversion
Showversionandexit.

shiftpositionalparameters
Outsideofafunction shift operatesonthecommandlinearguments.Insideafunction shift operatesonthe
functionarguments.

setpositionalparameters
Howtosetthepositionalparametersfromwithinascript.

getopts
Howtoprocesscommandlineoptions.

getopts operatesonthepositionalparameters$1,$2,

Thefirstargumentto getopts isawordspecifyingtheoptions.Theoptionsaresinglecharacterswhichcannotbe':'or


'?'.Thecolon':'indicatesthattheprecedingletterisanoptionwhichtakesanargument.Ifanoptionisencountered
whichisnotintheoptionword, getopts setsthevariableto'?'.

whilegetoptsa:b:c:defOPT
do
case$OPTin
a)OPTA=$OPTARG;;
b)OPTB=$OPTARG;;
c)OPTC=$OPTARG;;
d)OPTD=1;;
e)OPTE=1;;
f)OPTF=1;;
esac
done

ExecutionControl
bash fish ksh tcsh zsh
negateexitstatus !cmd notcmd !cmd !cmd
noopcommand : : : :
break break break break break break
switch(arg)
switcharg casepattern:
casepattern cmd
caseargin cmd caseargin caseargin
pattern)cmd;; pattern)cmd;; breaksw pattern)cmd;;
case
*)cmd;; case'*' *)cmd;; default: *)cmd;;
esac cmd esac cmd esac

end breaksw
endsw
continue continue continue continue continue continue
forvarinarg forvarinarg forvarinarg
forvarinarg foreachvar(arg)
do do do
cmd cmd
for cmd cmd cmd


end end
done done done
goto gotolabel
iftest iftest iftest
then iftest then if(expr)then then
cmd cmd cmd cmd cmd

eliftest elseiftest eliftest elseif(expr)then eliftest
then cmd then cmd then
cmd cmd cmd
if cmd cmd cmd

else
else

else cmd
else cmd
else
cmd cmd cmd
end
endif
fi fi fi

repeatcountdo
cmd
repeat repeatcountcmd

done
selectvarinarg selectvarinarg selectvarinarg
do do do
select cmd cmd cmd

done done done
untiltest untiltest untiltest
do do do
until cmd cmd cmd

done done done
whiletest whiletest whiletest
whiletest while(expr)
do do do
cmd cmd
while cmd cmd cmd


end end
done done done

negateexitstatus
Howtorunacommandandlogicallynegatetheexitstatus.Thiscanbeusefulifthecommandisrunastheconditional
ofa if statement.

The ! precommandmodifierconvertsazeroexitstatusto1andanonzeroexitstatusto0.

The ! mustbeseparatedfromthecommandbywhitespace,oritwillbeinterpretedbytheshellasahistory
substitution.

noopcommand
break
Exitstheenclosingfor,select,until,orwhileloop.

case
Thesyntaxforaswitchstatement.

Defaultclauses,whichareindicatedbythe*patterninmostshells,areoptional.

continue
Gotothenextiterationoftheenclosingfor,select,until,orwhileloop.

for
Aloopforiteratingoveralistofarguments.

zsh hasalternatesyntaxwhichusesparensinsteadofthe in keyword:

forVAR(ARG...)
do
CMD
...
done

goto
tcsh supportsthe goto statement.Thetargetthefirstlinecontainingjustthelabelfollowedbyacolon.Here'san
example:

#/bin/tcsh
gotofoo
echo"gotodoesn'twork!"
exit1
foo:
echo"gotoworks"

if
Theifstatement.

Thetestwhichistheargumentof if or elif canbeanysimplecommand,pipeline,orlistofcommands.Thetest


executesandiftheexitstatusiszerothecorrespondingclauseisalsoexecuted.

Oftenthetestwhichistheargumentof if or elif willbeoneofthetestoperators: test , [] , [[]] ,or (()) .

The elif and else clausesareoptional.


tcsh:

Theargumentof if and elif clausesmustbeanexpressioninsideparens.Unliketheothershellsitcannotbean


arbitrarycommand.Onecanthinkofexpressionsasbeingbuiltintothe tcsh shelllanguageratherthanbeing
delegatedtospecialized(albeitbuiltin)commandssuchas test and [] .

Notethatthe then keywordmustbeonthesamelineastheconditionalexpression.ThisisdifferentfromthePOSIX


syntaxwherethe then keywordisseparatedfromthetestcommandbyanewlineorsemicolon.

The elseif and else clausesareoptional.

tcsh hasthefollowingsyntaxforconditionallyexecutingasinglecommand:

if(EXPR)CMD

repeat
Hereareacoupleofwaystodosomething10timesifyouaren'tusing tcsh .NeithertechniqueisPOSIXcompliant,
however:

foriin`seq110`;doecho"la";done

foriin{1..10};doecho"la";done

select
Theselectstatementcreatesanumberedmenuinsideaninfiniteloop.Eachtimetheuserselectsoneofthenumbers
thecorrespondingcommandisexecuted.Theusercanuse^DorEOFtoexittheloop.

Oneachiterationvarissettothevaluecorrespondingtothenumbertheuserchose.The break keywordcanbeused


togivetheuseranumberedoptionforexitingtheloop.

until
Theremarksaboveonifconditionsalsoapplytotheuntilloopcondition.

while
Theremarksaboveonifconditionsalsoapplytothewhileloopcondition.

Redirection
bash fish ksh tcsh zsh
stdinfromfile trazAZ<file trazAZ<file trazAZ<file trazAZ<file trazAZ<file
stdouttofile ls>file ls>file ls>file ls>file ls>file
ls/not_a_file2> s/not_a_file2> ls/not_a_file2> ls/not_a_file2>
stderrtofile none
file file file file
stdoutandstderrtofile ls>file2>&1 ls>file2>&1 ls>file2>&1 ls>&file ls>file2>&1
appendstdouttofile ls>>file ls>>file ls>>file ls>>file ls>>file
appendstderrtofile ls2>>file ls2>>file ls2>>file none ls2>>file
appendstdoutandstderr ls>>/tmp/bash.out ls>>/tmp/bash.out ls>>/tmp/bash.out ls>>/tmp/zsh.out
ls>>&file
tofile 2>&1 2>&1 2>&1 2>&1
stdouttopipe ls|wc ls|wc ls|wc ls|wc ls|wc
sdoutandstderrtopipe ls2>&1|wc ls2>&1|wc ls2>&1|wc ls|&wc ls2>&1|wc
wc<<EOF wc<<EOF wc<<EOF wc<<EOF
do do do do
stdinfromheredocument re none re re re
mi mi mi mi
EOF EOF EOF EOF
stdinfromherestring wc<<<"doremi" none wc<<<"doremi" none wc<<<"doremi"
teestdout ls|teefile|wc ls>file|wc
stdouttotwofiles ls|teefile1|teefile2>/dev/null ls>file1>file2
turnonnoclobber setonoclobber setonoclobber setnoclobber setonoclobber
ls>! ls>! ls>! ls>!
clobberfileanyways
/tmp/exists.txt /tmp/exists.txt /tmp/exists.txt /tmp/exists.txt
turnoffnoclobber set+onoclobber set+onoclobber unsetnoclobber set+onoclobber

Agapintheabovechartishowtoredirectjuststderrtoapipe.Onewouldguessbyanalogywith 2> and 2>> thatthis


mightwork:

$ls2|wc

However,noneoftheshellssupportit.Thecorrectsyntaxis:

$ls3>&11>&22>&3|wc

The 3>&1 isequivalenttotheCsystemcall dup2(1,3) .Thismakesfiledescriptor3acopyoffiledescriptor1.


The 1>&2 isequivalenttotheCsystemcall dup2(2,1) .Thischangeswhatfiledescriptor1writesto,butdoesnot
changewhatfiledescriptor3writesto,eventhoughfiledescriptor3wasinitiallyacopyoffiledescriptor1.Theshell
processestheredirectstatementsfromlefttoright.Alsonotethatthe 1 couldbeomitted: 1>&2 and >&2 arethe
same.

zsh onlysupportsfiledescriptors0through9,but bash supportshighernumberedfiledescriptors.Theshellalways


opensfiledescriptors0,1,and2,commonlycalled stdin , stdout ,and stderr ,foreachsimplecommandthatit
invokes.Ifadditionalfiledescriptorsarespecified,thosearealsopassedtothecommand.Forexample,if foo were
invokedas:

$foo3>/tmp/bar.txt

thenitcouldcontainasystemcallwhichwritestofiledescriptor3withoutopeningitfirst,e.g.

write(3,msg,strlen(msg));

Pathsinthe /dev directorycanbeusedinplaceof &1 , &2 ,

$ls3>/dev/fd/11>/dev/fd/22>/dev/fd/3|wc

$ls3>/dev/stdout1>/dev/stderr2>&3|wc

tcsh:

Itispossibletoredirectstdoutandstderrtodifferentfiles:

$(ls>/tmp/stdout.txt)>&/tmp/stderr.txt

EchoandRead
bash fish ksh tcsh zsh
echo echoarg echoarg echoarg echoarg echoarg
withnewline,withoutnewline echonarg echonarg echonarg echonarg echonarg
printffmt printffmt printffmt printffmt
printf printffmtarg
arg arg arg arg
read readvar
readvar readvar readvar
readpstr echonstr
readp'echostr' readvar?str readvar\?str
readvaluesseparatedbyIFSwithpromptwithout var setvar=$<
var readrvar readrvar
backslashescape readrvar

echo
Howtoechotheargumentsseparatedbyspacesandfollowedbyanewlinehowtosuppressthetrailingnewline.

ThePOSIXstandardsaysthat echo shouldnothaveanyoptions.Italsosays,perhapscontradictingitself,thatifthe


firstargumentis n thenthebehaviorisimplementationdependent.

ThePOSIXstandardalsosaysthatifanyoftheargumentscontainbackslashes,thenthebehaviorisimplementation
dependent.Historicallyimplementationshaveusedthe E and e optionstoenableordisabletheinterpretationofC
stylebackslashescapesequences.

fish providesan s optionforprintingtheargumentswithoutspacesinbetween.

Becauseiftheilldefinedbehaviorof echo ,POSIXcompliantscriptsuse printf instead.

printf
printf isanexternalcommandlinetool,though zsh alsohasabuiltinversion.

man3printf

LikeitscounterpartfromtheCstandardlibrary, printf doesnotwriteanewlinetostdoutunlessoneisspecifiedinthe


formatusingabackslashescapesequence.

Unfortunately,thesupportedbackslashecscapesaresystemdependent,thoughsomeofthemaremandatedbyPOSIX:

posix bsd gnu


\a\b\c\f\n\r\t\v\\ \a\b\c\f\n\r\t\v\\\' \a\b\c\e\f\n\r\t\v\\\"
backslashescapes
\o\oo\ooo \o\oo\ooo \o\oo\ooo\xhh\uhhhh\Uhhhhhhhh

Aninterestingbackslashescapeis\c,whichcausestherestoftheformattobeignored.

Inaprintfformat,formatspecifiersareoftheform %d , %f and %s .

posix bsd gnu


diouxX diouxX
formatspecifiers fFaAeEgG feEgG
csb csb

formatspecifiersmanyofwhichareuselessinthiscontextbecauseoffewertypes

howinvalidargumentsarehandled

%%

extraspecifierswithfloats
extraspecifierswithstrings

read
Howtoreadalineofinputintooneormorevariables.

Whenmultiplevariablesarespecifiedthevalueof IFS whichbydefaultcontainsthewhitespacecharactersisusedto


splittheinput.Iftherearefewervariablesthansplitvalues,thenthelastvariablewillcontainaconcatenationofthe
remainingvalueswiththeiroriginalseparators.Iftherearefewervaluesthentheextravariablesaresettotheempty
string.

bash and dash usethe p optiontosetaprompt. ksh and zsh usea?strsuffixappendedtothefirstvariabletoset


theprompt.

fish usesthe p option,butitevaluatesthestringtoproducetheprompt.Thismakesitpossibletosetthecolorof


theprompt:

readp'set_colorgreen;echon">";set_colornormal'foo

Theusercanputabackslashinfrontofanewlinetosplittheinputupovermultiplelines.Thebackslashandnewlineare
strippedfromtheinput.Theusercanputbackslashintothevariablebyenteringtwobackslashes.The r option
disablesthisfeature,allowingtheusertoenterliteralbackslasheswithasinglekeystroke.

tcsh getsinputfromtheuserbyreadingfromthespecialvariable $< .Backslashesarealwaysinterpretedliterally.

FilesandDirectories
bash fish ksh tcsh zsh
cddir cddir cddir cddir cddir
changecurrentdirectory cd cd cd cd cd
cd cd cd cd cd
changedir,tohomedir,topreviousdir,showphysicaldir,nosymlinkdir cdPdir none cdPdir none cdPdir
none none none none cdsdir
directorystack: pushddir pushddir pushddir pushddir
popd popd popd popd
push,pop,list dirs dirs dirs dirs
printcurrentdirectory pwd pwd pwd pwd pwd
sourcefile source sourcefile sourcefile
sourcefile
source arg file arg arg
arg
.filearg .file .filearg .filearg
umask022 umask022 umask022 umask022
umask umask022
umaskgw,o umaskg umaskgw,o umaskgw,o
none
w w,ow w w
setumaskinoctal,insymbolicchmodformatshowumaskinoctal,in umask
umask umask umask umask
symbolicchmodformat none
umaskS umaskS umaskS umaskS

changecurrentdirectory
Changethecurrentdirectorytothespecifieddirectory.Ifthedirectorystartswithaslash'/'thenitistakentobean
absolutepath.IfitdoesnotitistreatedasarelativepathandCDPATHisusedasacolonseparatedlistofstarting
directories.BydefaultCDPATHisemptyinwhichcasethecurrentdirectory'.'isusedasastartingpoint.Seealsothe
sectionontildeexpansion.

Ifthereisnoargumentthenthecurrentdirectoryischangedto$HOME.

Iftheargumentisahyphen''thenthecurrentdirectoryischangedto$OLDPWDwhichisthemostrecentformer
currentdirectory.

Whenthe P optionisused, PWD willbesettothephysicalpathofthecurrentdirectoryi.e.anysymboliclinkswillbe


resolved.Ifthecurrentdirectoryisbeingdisplayedinthepromptthiswillalsobesetthephysicalpath.

zsh:

Whenthe s optionisused,attemptingtochangedirectoryintoapathcontainingsymlinkswillfail.

directorystack
Pushadirectoryprovidedasanargumentontothedirectorystack.Thedirectorybecomesthecurrentdirectory.

Popadirectoryoffthedirectorystack.Thepoppeddirectorybecomesthecurrentdirectory.

Listthedirectorystack.

printcurrentdirectory
Showthecurrentdirectory.Thesameasexecuting:

echo$PWD

source
The source builtinexecutesthecommandsinanotherfileusingthecurrentshellprocessandenvironment.

SomeshellshaveanonPOSIXfeaturewhichallowsargumentstobepassedtothefilebeingsourcedi.e.thefollowing
invocationwouldset $1 , $2 ,and $3 to bar , baz ,and quux whileexecuting foo.sh :

sourcefoo.shbarbazquux
The . syntaxispartofthePOSIXstandard,butthe source syntaxisnot.

Thefiletobesourcedmaybespecifiedwithanabsolutepath.Someshellswillalsosearchtheworkingdirectoryor
PATH forthefiletobesourced:

bash fish ksh tcsh zsh


searchesworkingdirectory yes yes no yes .no,sourceyes
searchesPATH yes no no no yes

umask
Settheshellfilemodecreationmask. umask isaPOSIXsyscall.

Themaskconsistsof3octaldigitswhichapplytotheuser,group,andotherpermissionsrespectively.Eachoctaldigit
contains3bitsofinformation.Inorderofmosttoleastsignificantthebitsapplytotheread,write,andexecute
permissions.

Settingabitinthemaskguaranteesthatthecorrespondingbitinthefilepermissionswillnotbesetwhenafileis
created.Thelogicforcomputingthefilepermissionscanbeexpressedwiththefollowingshellcode:

mask=8#022
perms=8#777

printf"0%o\n"$(($perms&~$mask))

HereisthesamelogicinCcode:

unsignedintmask=0022;
unsignedintperms=0777;

printf("%o\n",perms&~mask);

If umask isgivenanumericargumentitisalwaysinterpretedasoctalaleadingzeroisnotrequired.

umask alsosupportsthesymbolicnotationusedbychmod.Inthiscasetheargumentisoneormore3character
sequencesoftheformat [agou][+][rwx] separatedbycommas.

ProcessandJobControl
bash fish ksh tcsh zsh
runjobin
bg bg bg bg bg
background
protectjob
doesnotSIGHUP
fromhangup disown disown disown
backgroundjobsonexit
signal
executefile exec[c] exec exec exec exec
exit
exit exit[n] exit exit exit
bye
runjobin
fg fg fg fg fg
foreground
hup
listjobs jobs[lnprs] jobs jobs jobs jobs
external,but
sendsignal kill kill kill kill
kill
limit limit
login
logout logout logout
nice
nohup
onintr
sched sched
sleep
stop
suspend suspend suspend suspend
time time time
times times times
trap trap trap trap
ulimit ulimit ulimit
ulimit unlimit unlimit
wait wait wait wait
______________________ ______________________ ______________________ ______________________ ______________________

xargs splitsstandardinputonspacesandnewlinesandfeedstheargumentstoargumentof xargs whichisexecuted


asacommand.Theinputdelimitercanbechangedtonullcharacterswiththe0flag(usefulwith findprint0 )orto
thevalueofthedflagargument.

Bydefaultifthelengthoftheinputismorethan4096characterstheinputwillbebrokenupandthecommandrun
multipletimes.ThisnumbercanbeincreasedwiththesflaguptosystemconfigurationvariableARG_MAX.Itisalso
possibletocallthecommandmultipletimesfeedingitaprescribednumberofargumentseachtimeusingthenflag.
Thetflagwillwritetostandarderrorthecommandthatisbeinginvokedanditsargumentsbeforeeachinvocation.
ThePflagcanbeusedtoforparallelization.Theargumentisthemaxnumberofsimultaneousprocesses.

runjobinbackground

protectjobfromhangupsignal
executefile

History
historycommands
bash fish ksh tcsh zsh
history history
fcl history|nl|head
commandhistory: ?? 15 history1
history history|nl
fcl1 history history
set cat
listrecent,listall,listwithtime,unnumbered none history f
HISTTIMEFORMAT ~/.config/fish/fish_history
list ?? T history
fcln history
none n
commandhistory:
!num rnum none !num
fcsstr fcs none ??
run,findandrun
commandhistory: none
historydnum none none
history
historyc none none
deletefromhistory,clearhistory c
commandhistory: fcnum
fcnum fcnum
fcsold=new
fcsold=newstr none
fix,findandsubstitute str
fcW
path
commandhistory: historywpath
fcA
historyapath
path
writetofile,appendtofile,readfromfile historyrpath
fcR
path

commandhistory:listing
Howtolistrecentcommandshowtolistallcommandshowtolistcommandswiththetimetheywererun.

commandhistory:running
Howtorunacommandinthehistorybycommandnumberhowtorunthemostrecentcommandinthehistorymatching
aprefix.

commandhistory:deleting
Howtodeleteacommandfromthehistorybycommandnumberhowtoclearthecommandhistory.

commandhistory:fixing
Usethefollowingsyntaxtoeditcommandsfromthehistorylistandrunthem:

fc[eEDIT_CMD][r][FIRST[LAST]]

IfEDIT_CMDisnotspecified,thevalueintheFCEDITorEDITORenvironmentvariableisused.

IfFIRSTandLASTarespecified,theseindicatethenumbersoftherangeofcommandstoedit.IfFIRSTisspecified
butLASTisnot,onlythatcommandatthatnumberiseditedandrun.Ifneitherisspecifiedthelastcommandisedited
andrun.

Therflagreversestheorderofthecommands.

Tosimplylistcommandsthefollowingflagscanbeused:

fcl[r][FROM]
fcl[r]NUMBER_CMDS

IfneitherFROMnorNUMBER_CMDSisspecifiedthelast16commandsisprinted.UseNUMBER_CMDS(i.e.a
negativenumber)tolistthelastNUMBER_CMDScommands.UseFROM(i.e.apositivenumber)tolistallcommands
fromFROMon.

Therflagreversestheorderofthecommands

Torerunarecentcommandwithouteditingituse:

fcs[PAT=REP][START_OF_CMD]

IfSTART_OF_CMDisspecifiedthelastcommandthatstartswithSTART_OF_CMDwillberun.IfSTART_OF_CMDis
notspecifiedthelastcommandwillberun.

IfPAT=REPisspecifiedtheneachoccurrenceofPATwillbereplacedwithREPinthecommandbeforeitisrun.

ksh:

hist isasynonymfor fc withthesoledifferencethatHISTEDITistheenvironmentvariablethatdeterminestheeditor


insteadofFCEDIT.
zsh:

r isanaliasfor fcs

commandhistoryfile
historyexpansion
bash fish ksh tcsh zsh
mostrecentcommand !! none none !! !!
nthcommand !n none none !n !n
mostrecentcommandstartingwithstr !str none none !str !str
mostrecentcommandwithsubstitution ^pattern^replacement none none ^pattern^replacement ^pattern^replacement
nthcommandwithsubstitution !n:s/pattern/replacement/ none none !n:s/pattern/replacement/ !n:s/pattern/replacement/
nthcommandwithglobalsubstitution !n:gs/pattern/replacement/ none none !n:gs/pattern/replacement/ !n:gs/pattern/replacement/
mostrecentarguments !* none none !*
firstofmostrecentarguments !:1 none none !:1
rangeofmostrecentarguments !:nm none none !:nm
lastofmostrecentarguments !$ none none !$
mostrecentcommandwithoutarguments !:0 none none !:0
mthargumentofnthcommand !n:m none none !n:m

historyfile
bash fish ksh tcsh zsh
sethistfile
location HISTFILE=~/.bash_history ~/.config/fish/fish_history HISTFILE=~/.ksh_history HISTFILE=~/.zsh_history
~/.tcsh_history
memory
HISTSIZE=2000 HISTSIZE=2000 HISTSIZE=2000
size
set
filesize HISTFILESIZE=2000 SAVEHIST=2000
savehist=2000
format linesofinput
timestamps HISTTIMEFORMAT=%s
updatetime onexit onexit
appendsto
file;
tosortin
memoryfileand
appendstofile; mostrecentby
update toonlykeepmostrecent timestampand
method dupe: onlykeepthe
HISTCONTROL=erasedups mostrecent,
use:
set
savehist=2000
merge
ignore HISTIGNORE=history:whoami

KeyBindings
bash fish ksh tcsh zsh
listkeybindings bindP bind bindkey bindkey
listkeymaps helpbind none none bindkeyl
currentkeymapname bindV|grepkeymap none none
changekeymap bind'setkeymapemacs' none none bindkeyAemacsmain
listbindablefunctions bindl bindf bindkeyl
bindkeytofunction bindCa:beginningofline bind\cabeginningofline
restoredefaultbindingforkey

bashandzshhavekeymaps

howtocreateanewkeymapwithzsh

alternatefishsyntaxreferringtokeys

StartupFiles
bash fish ksh tcsh zsh
/etc/csh.cshrc
/etc/zshenv
noninteractiveshellstartupfiles $BASH_ENV ~/.config/fish/config.fish $ENV ~/.tcshrc
$ZDOTDIR/.zshenv
~/.cshrc
noninteractivestartup
files
/etc/profile /etc/zprofile
/etc/profile
~/.bash_profile /etc/csh.login $ZDOTDIR/.zprofile
loginshellstartupfiles ~/.config/fish/config.fish ~/.profile
~/.bash_login ~/.login /etc/zshrc
$ENV
~/.profile $ZDOTDIR/.zshrc
/etc/zlogin
$ZDOTDIR/.zlogin
noninteractivestartup
otherinteractiveshellstartup files
files ~/.bashrc ~/.config/fish/config.fish $ENV none
/etc/zshrc

$ZDOTDIR/.zshrc
/etc/csh.logout $ZDOTDIR/.zlogout
loginshelllogoutfiles ~/.bash_logout none none
~/.logout /etc/zlogout

bash:

Whenloggingin bash willonlyexecuteoneof ~/.bash_profile , ~/.bash_login ,or ~/.profile .Itexecutes


thefirstfilethatexists.

fish:

Thestartupfile .config/fish/config.fish isrunbyallshells.Hereishowtoputcodeinitwhichonlyexecutes


atlogin:

ifstatusislogin
setPATH$PATH~/bin
end

Howtodefineanexithandler:

functionon_exitonprocess%self
echofishisexiting...
end

PromptCustomization
bash fish ksh tcsh zsh
functionfish_prompt
PS1='$
setprimaryprompt PS1='$' echon'$' setprompt='$' PS1='$'
'
end
PS2='>
setcontinuedlineprompt PS2='>' none setprompt2='>' PS2='>'
'
PS='?
setselectprompt PS3='?' none none PS3='?'
'
functionfish_right_prompt
setrprompt='%Y%W
setrightprompt none date RPS1='%D{%F%T}'
%D%p'
end
setrightcontinuedlineprompt none none none RSP2='...'
dynamicinformation
%d
workingdirectory none pwd %/
%/
abbreviatepathcomponents
other
workingdirectorywithtilde
\w thanbasenamewithsingle %~ %~
abbrev
letter:
prompt_pwd
trailingcomponentsofworking
%3C %3d
directory
!
%!
commandnumberinhistory \! ! %!
%h
%h
commandnumberinsession \#
shellversion \v
shelllevel $SHLVL
environmentvariable $var echon$var $var %$var $var
commandsubstitution $(cmd) $(cmd) $(cmd)
\h %m
hostname
\H %M
user \u %n %n
numberofjobs \j %j %j
tty %y
lastcommandexitstatus %? %?
conditionalexpression
shellprivilegeindicator %#
continuedlineinfo
dateandtime \D{strftime_format} %D{strftime_format}
texteffectsandescapes
escapes \\\[\] %%%{%} %%%{%}
bold %B%b %B%b
underline %U%u %U%u
standout %S%s %S%s
foregroundcolor %F{red}%f
backgroundcolor %K{green}%k

Mostshellspermitausertocustomizethepromptbysettinganenvironmentvariable. fish requiresthattheuser


defineacallbackfunction.

Theprimarypromptistheprompttheuserseesthemostoften.
Thecontinuedlinepromptisusedwhentheusertypesanincompletecommand.Thiscanhappenwhenthereareopen
parens,braces,orquoteinthecommand,ortheuserbackslashescapedthenewline.

Theselectpromptisusedtoprompttheusertomakeamultiplechoiceselection.Itcorrespondstotheselectexecution
controlstatement.

Therightpromptappearsatthefarrightsideoftheinputline.Iftheusertypesenoughinputtoneedthespace,theright
promptdisappears.

dynamicinformation
bash , tcsh ,and zsh provideasetofspecialcharactersequencesforputtingdynamicinformationintheprompt.In
thecaseof bash thesequencesstartwithabackslashandinthecaseof tcsh and zsh apercentsign.

bash , ksh , tcsh ,and zsh willalsoperformvariableexpansiononanythingthatstartswithadollarsignandlooks


likeavariablebeforeeachdisplayoftheprompt. bash , ksh ,and zsh willalsoperformcommandsubstitutionbefore
eachdisplayofthepromptwhentheyencounterthe $() syntaxintheprompt.

texteffectsandescapes

Autoload
fish:

zsh:

bash(1989)
bash

TheBourneAgainshellisaGNUreplacementfortheBourneshell.ItcanrunalmostallBournescriptsandPOSIX
compliantscripts,andoperatingsystemsoftenuse bash as /bin/sh .Because bash hasmanyextensionsitisnot
agoodshelltousefordeterminingPOSIXcompliance.

csh(1978)
csh

TheCshellwaswrittenbyBillJoyandreleasedaspartofthesecondBerkeleyStandardDistribution.

Itintroducedfeaturesthatwerewidelyadoptedbyothershells:historyexpansion,aliases,tildenotation,andjobcontrol.

TheCshellwassonamedbecauseitlookedmorelikeCthantheBourneshell.Itstillusedkeywordstomarkoffblocks
insteadofcurlybraces,butitsexpressionsweredelimitedbyparensinsteadofsquarebracketsandrelationaloperators
suchas<and<=couldbeusedinsteadofltandle.TheUnixcommunityneverthelesseventuallychoseaderivation
oftheBourneshellasthestandardscriptinglanguageandwritingscriptsfortheCshellisnotrecommended.

TheclassicMacintoshoperatingsystemhadadevelopmentenvironmentcalledTheMacProgrammer'sWorkbench.It
includedashellthatwasderivedfromtheCshell.

dash(2002)
dash

TheDebianAlmquistshell, dash ,wasoriginallyaLinuxportoftheNetBSDAlmquistshell, ash .ItisPOSIX


compliant.Itisalsosmallerthantheothershells:onUbuntuLinuxtheexecutableisabout100kwhereastheothershells
areinthe300k900krange.

dash doesnotkeepacommandhistoryoroffercommandlineediting.Itdoeshavejobcontrol,though.

fish(2005)
Fishuserdocumentation

ksh(1983)
ksh

TheKornshelladdedhistoryandjobcontrolbutotherwisestayedconsistentwiththeBourneshell.ThePOSIXstandard
fortheshellwasbasedontheKornshell.

TheKornshellwasproprietarysoftwareuntil2000,whichiswhyclonessuchas pdksh werewritten.Also, zsh canbe


usedtoemulate ksh bothMacOSXandUbuntulink ksh to zsh .

rc(1989)
The rc shellwasreleasedaspartof10thEditionUnix.ItwasalsothePlan9shell.

sh
POSIX2008

Asuccessionofshellshavebeeninstalledat /bin/sh whichareknowntodaybytheengineerswhoimplemented


them:theThompsonshell,theMasheyshell,andtheBourneshell.

TheBourneshellappearedin1977.Itintroducedtheexecutioncontrolstructuresthatareusedinmostofthemodern
Unixshells.Thesecontrolstructures,withtheirdistinctivereversedwordsformarkingtheendofblocks: fi and esac ,
wereborrowedfromAlgol68.However,whereAlgol68uses od theBourneshelluses done .ThiswasbecauseaUnix
commandnamed od alreadyexisted.TheBourneshellalsointroducedarbitrarylengthvariablenamestheMashey
shellbycontrastwaslimitedtosinglelettervariablenames.

Whateverisinstalledat /bin/sh shouldprobablybePOSIXcompliant.MacOSXuses bash ,whichchangesits


behaviorsomewhatandoperatesinPOSIXmodewheninvokedas sh .Onecanalsogetthisbehaviorbyinvoking
bash withthe posix flag.

Ubuntumakes /bin/sh asymlinkto /bin/dash .

tcsh(1981)
tcsh

TheTENEXCshell, tcsh ,wasupgradedversionoftheCShellwhichaddedtabcompletion,afeatureoriginallyusedin


theTENEXoperatingsystem.

tcsh isbackwardlycompatiblewith csh andonmanysystems csh issimplyasymlinkto tcsh .

tcsh isthedefaultshellonFreeBSDanditwasthedefaultshellonMacOSXuntilversion10.3wasintroducedin
2003.

Writingscriptsin tcsh isnotrecommendedforthesamereasonswritingscriptsin csh isnotrecommended.

Thefollowing tcsh builtinsinteractwiththeterminalsettings:

echotc
settc
setty
telltc
termname

zsh(1990)
TheZshell, zsh ,isdocumentedbymultiplemanpages:

manpage topicscovered
zshall alltopicsinonemanpage
zsh startupfiles
zshoptions options
zshbuiltins builtins
zshcompwid,zshcompsys tabcompletion
zshcompctl oldtabcompletionsystem
zshexp historyexpansion;parameterexpansion;process,tilde,command,andpathnameexpansion
zshmisc grammar;keywords;quoting;redirection;arithmeticandconditionalexpressions;promptcustomization
zshparam specialvariables
zshzle readline

zsh hasthesebuiltinsformanagingthecompletionmodule:

comparguments
compcall
compctl
compdescribe
compfiles
compgroups
compquote
comptags
comptry
compvalues

Thefollowing zsh builtinsinteractwiththeterminalsettings:

echotc
echoti
getcap
ttyctl

Special zsh builtins:

autoload
zcompile
zformat
zmodload
zparseopts
zstyle

issuetracker|contentofthispagelicensedundercreativecommonsattributionsharealike3.0

You might also like