This index / glossary / quick-reference lists many of the
important topics covered in the text. Terms are arranged
in approximate ASCII sorting order,
modified as necessary for enhanced
clarity.Note that commands are indexed
in Part 4.* * *^ (caret)
Beginning-of-line,
in a Regular Expression
^^^Uppercase
conversion in parameter
substitution~ Tilde~
home directory, corresponds
to $HOME~/ Current user's
home directory
~+ Current
working directory
~- Previous
working directory
= Equals sign
=
Variable assignment operator
=
String comparison operator
==
String comparison operator
=~ Regular Expression
match operator
Example
script< Left angle bracket
Is-less-thanString comparison
Integer comparison within
double parentheses
Redirection< stdin<< Here document<<< Here string<>
Opening a file for
both reading and writing
> Right angle bracket
Is-greater-thanString comparisonInteger comparison,
within double parenthesesRedirection>
Redirect
stdout to a file
>>
Redirect
stdout to a file,
but appendi>&j
Redirect
file descriptori to
file descriptorj>&j
Redirect
stdout to
file descriptorj>&2
Redirect
stdout of a command to
stderr2>&1
Redirect
stderr
to stdout&>
Redirect
bothstdout
and stderr of a command to a
file:> file
Truncate file
to zero length|
Pipe, a device for passing the output
of a command to another command or to the shell||
Logical OR test operator- (dash)
Prefix to default
parameter, in parameter
substitution
Prefix to option
flag
Indicating
redirection from
stdin or stdout-- (double-dash)Prefix to
long command optionsC-style
variable decrement within double
parentheses
; (semicolon)
As command
separator\; Escaped semicolon,
terminates a find
command;;
Double-semicolon, terminator in a
case optionRequired when ...do
keyword is on the first line of
loop
terminating curly-bracketed
code block;;&;&
Terminators in
a case option (version 4+ of Bash).: Colon
:> filename
Truncate file
to zero lengthnull
command, equivalent to the
true Bash
builtinUsed in an anonymous
here documentUsed in an otherwise
empty functionUsed as a function
name!
Negation operator, inverts exit status of a test or command
!=
not-equal-to
String comparison operator? (question mark)
Match zero or one characters,
in an Extended Regular
ExpressionSingle-character
wild card,
in globbingIn a
C-style
Trinary operator//
Double forward slash,
behavior of cd command toward. (dot / period)
.
Load a file (into a script),
equivalent to source command
.
Match single character,
in a Regular Expression
.
Current working
directory
./
Current working
directory
.. Parent
directory
' ... '
(single quotes)
strong
quoting" ... "
(double quotes)
weak
quoting
Double-quoting
the backslash (\)
character,
Comma operator
,,,Lowercase
conversion in parameter
substitution() Parentheses
( ... )
Command group;
starts a
subshell( ... )
Enclose group
of Extended Regular
Expressions>( ... )<( ... )
Process substitution ... )
Terminates test-condition
in case construct(( ... ))
Double parentheses,
in arithmetic expansion[ Left bracket,
test construct[ ]Brackets
Array
elementEnclose character set
to match in a Regular
ExpressionTest construct[[ ... ]]
Double brackets,
extended test construct$ Anchor,
in a Regular Expression$
Prefix to a variable name$( ... )
Command substitution,
setting a variable with output of a command,
using parentheses notation` ... `
Command substitution,
using backquotes
notation$[ ... ]
Integer expansion
(deprecated)${ ... } Variable manipulation / evaluation
${var}
Value of a variable${#var}
Length of a variable${#@}${#*}
Number of
positional
parameters${parameter?err_msg}
Parameter-unset
message${parameter-default}${parameter:-default}${parameter=default}${parameter:=default}
Set default
parameter${parameter+alt_value}${parameter:+alt_value}Alternate value
of parameter, if set${!var}Indirect referencing of a variable,
new notation${!#}Final positional
parameter.
(This is an indirect reference to
$#.)${!varprefix*}${!varprefix@}Match
names of all previously declared
variables beginning with varprefix${string:position}${string:position:length}
Substring
extraction${var#Pattern}${var##Pattern}
Substring
removal${var%Pattern}${var%%Pattern}
Substring
removal${string/substring/replacement}${string//substring/replacement}${string/#substring/replacement}${string/%substring/replacement}
Substring
replacement$' ... '
String expansion,
using escaped characters.\
Escape the character following
\< ... \>
Angle brackets,
escaped,
word boundary in a Regular
Expression\{ N \}Curly brackets,
escaped,
number of character sets to match in an Extended RE\; Semicolon,
escaped,
terminates a find
command\$$ Indirect
reverencing of a variable, old-style notationEscaping
a newline,
to write a multi-line command& &>
Redirect
bothstdout
and stderr of a command to a
file>&j
Redirect
stdout to
file descriptorj>&2
Redirect
stdout of a command to
stderri>&j
Redirect
file descriptori to
file descriptorj2>&1
Redirect
stderr to
stdoutClosing file
descriptorsn<&-
Close input file descriptor
n0<&-,
<&-
Close stdinn>&-
Close output file descriptor
n1>&-,
>&-
Close stdout&&
Logical AND
test operatorCommand &
Run job in
background#
Hashmark,
special symbol beginning a script
comment#!
Sha-bang,
special string starting a
shell script* Asterisk
Wild
card,
in globbing
Any number of characters
in a Regular Expression
**
Exponentiation,
arithmetic operator
**
Extended globbing
file-match operator
% Percent sign
Modulo, division-remainder
arithmetic operation
Substring removal
(pattern matching) operator+ Plus sign
Character
match, in an extended Regular
ExpressionPrefix to
alternate parameter, in
parameter substitution ++ C-style
variable increment, within
double
parentheses* * *Shell Variables$_
Last argument to previous
command$-
Flags passed to script, using set$! Process ID
of last background job$? Exit
status of a command$@
All the positional parameters, as separate
words $*
All the positional parameters, as a single
word$$
Process ID of the
script$#
Number of arguments passed to a
function, or to the script
itself$0
Filename of the script$1
First argument passed to script$9
Ninth argument passed to scriptTable
of shell variables* * * * * *-a
Logical AND
compound comparison testAddress database, script
exampleAdvanced Bash Scripting Guide,
where to downloadAlias
Removing an
alias, using
unaliasAnagrammingAnd list
To supply default command-line
argumentAnd logical
operator &&Angle brackets,
escaped,
\< . . . \>
word boundary in a Regular
ExpressionAnonymous
here document, using
:Archiving
rpmtarArithmetic expansion
exit status of
variations ofArithmetic operators
combination operators, C-style += -= *= /= %= In certain contexts,
+= can also function as a string
concatenation operator.ArraysAssociative arrays
more efficient
than conventional arraysBracket notation
Concatenating,
example scriptCopying
Declaringdeclare -a
array_nameEmbedded
arraysEmpty
arrays, empty elements, example
scriptIndirect references
Initializationarray=( element1 element2 ... elementN)Example
scriptUsing command
substitutionLoading a
file into an arrayMultidimensional,
simulatingNesting and
embeddingNotation
and usageNumber of elements in${#array_name[@]}${#array_name[*]}OperationsPassing
an array to a
functionAs
return value from
a functionSpecial properties,
example
scriptString operations,
example
scriptunset deletes array
elementsArrow keys, detectingASCII
Definition
Scripts for generating ASCII tableawk field-oriented text
processing language
rand(),
random functionString
manipulationUsing
export to pass a variable to an
embedded awk script* * *Backlight, setting the
brightnessBackquotes,
used in command
substitutionBase conversion,
example scriptBash
Bad scripting
practicesBasics reviewed,
script exampleCommand-line
optionsTable Features that classic
Bourne shell lacksInternal variables
Version 2
Version 3Version 4Version 4.1Version 4.2.bashrc$BASH_SUBSHELLBasic commands, externalBatch files,
DOSBatch processingbc, calculator utility
In a here
documentTemplate
for calculating a script variableBibliographyBison utilityBitwise operators
Example script
Block devices
testing
forBlocks of code
Iterating / loopingRedirectionScript example:
Redirecting output of a a code
blockBootable flash drives, creatingBrace expansion
Extended,
{a..z}Parameterizing
With increment and
zero-padding (new feature in Bash, version
4)Brackets, [ ]Array
elementEnclose character set
to match in a Regular
ExpressionTest constructBrackets, curly, {},
used inCode
blockfindExtended Regular
ExpressionsPositional
parametersxargsbreak
loop control command
Parameter
(optional)Builtins in
BashDo not fork a subprocess
* * *case
construct
Command-line parameters,
handlingGlobbing,
filtering strings withcat,
concatentate file(s)
Abuse ofcat
scriptsLess efficient than
redirecting stdinPiping the output
of, to a readUses ofCharacter devices
testing
forChecksumChild processesColon, : ,
equivalent to the true Bash
builtinColorizing scripts
Cycling through the background colors, example scriptTable of
color escape sequencesTemplate,
colored text on colored backgroundComma operator,
linking commands or operationsCommand-line optionscommand_not_found_handle ()
builtin error-handling function
(version 4+ of Bash)Command substitution
$( ... ),
preferred notationBackquotesExtending the
Bash toolsetInvokes a
subshellNestingRemoves trailing newlines
Setting variable from loop output
Word
splittingComment headers,
special purposeCommenting out blocks of code
Using an anonymous here
documentUsing an
if-then constructCommunications and
hostsCompound comparison
operatorsCompression utilities
bzip2compressgzipzipcontinue loop control commandControl characters
Control-C,
breakControl-D,
terminate / log out / eraseControl-G,
BEL
(beep)Control-H,
ruboutControl-J,
newlineControl-M,
carriage returnCoprocessescron, scheduling
daemonC-style syntax
, for handling variablesCrossword puzzle solverCryptographyCurly brackets {}
in
find commandin an
Extended Regular
Expressionin
xargs* * *Daemons, in UNIX-type OSdatedc, calculator utilitydd, data
duplicator command
ConversionsCopying raw data
to/from devicesFile deletion,
secureKeystrokes, capturingOptionsRandom access on a data
streamRaspberry Pi,
script for preparing a bootable SD
card
Swapfiles, initializingThread on
www.linuxquestions.orgDebugging scripts
ToolsTrapping at
exitTrapping
signalsDecimal number,
Bash interprets numbers asdeclare builtinoptionscase-modification
options (version 4+ of Bash)
Default parameters/dev directory
/dev/null
pseudo-device file/dev/urandom
pseudo-device file, generating pseudorandom numbers
with/dev/zero,
pseudo-device fileDevice filedialog,
utility for generating dialog boxes in
a script$DIRSTACKdirectory stackDisabled commands,
in restricted shellsdo keyword,
begins execution of commands within a loopdone keyword,
terminates a loopDOS batch
files, converting to shell scriptsDOS
commands, UNIX equivalents of
(table)dot files,
hidden setup and configuration filesDouble brackets
[[ ... ]] test
constructand evaluation of
octal/hex constantsDouble parentheses
(( ... )) arithmetic expansion/evaluation
constructDouble quotes
" ... "weak quoting
Double-quoting
the backslash (\)
characterDouble-spacing a text
file, using sed* * *-e
File exists testecho
Feeding commands down
a pipeSetting a variable
using command
substitution/bin/echo,
external echo commandelif,
Contraction of else
and ifelseEncrypting files, using opensslesac, keyword terminating
case constructEnvironmental
variables -eq ,
is-equal-to integer
comparison testEratosthenes,
Sieve of, algorithm for generating prime numbersEscaped characters,
special meanings of
Within $' ... '
string expansionUsed with
Unicode characters/etc/fstab
(filesystem mount) file/etc/passwd
(user account) file$EUID,
Effective user IDeval,
Combine and evaluate expression(s),
with variable expansion
Effects
of, Example scriptForces
reevaluation of
argumentsAnd indirect
referencesRisk of
usingUsing
eval to convert array
elements into a command listUsing
eval to select among
variablesEvaluation of
octal/hex constants within
[[ ... ]]exec command,
using in redirectionExercisesExit and Exit status
exit
commandExit status
(exit code, return
status of a command)Table,
Exit
codes with special meanings
Anomalous
Out of rangePipe
exit status
Specified by a function
returnSuccessful,
0/usr/include/sysexits.h,
system file listing C/C++ standard exit codesExport,
to make available variables to child processes
Passing a variable
to an embedded awk
scriptexpr,
Expression evaluator
Substring
extractionSubstring
index (numerical position in
string)Substring
matchingExtended Regular
Expressions? (question mark)
Match zero / one characters
( ... )
Group
of expressions\{ N \}Curly brackets,
escaped,
number of character sets to match+ Character
match* * *factor, decomposes an
integer into its prime factors
Application: Generating
prime numbersfalse,
returns unsuccessful (1) exit statusField, a group of characters
that comprises an item of dataFiles / ArchivingFile descriptorsClosingn<&-
Close input file descriptor n0<&-,
<&-
Close stdinn>&-
Close output file descriptor n1>&-,
>&-
Close stdoutFile handles in
C, similarity toFile encryptionfind
{}
Curly
brackets\; Escaped
semicolonFilter
Using -
with file-processing utility as a filter
Feeding output of a filter back to same
filterFloating point numbers,
Bash does not recognizefold, a filter to wrap lines of
textForking a child
processfor
loopsFunctionsArguments
passed referred to by positionCapturing
the return value of a function
using echoColon
as function nameDefinition
must precede first call to functionExit
statusLocal variablesand recursionPassing
an array to a
functionPassing pointers
to a functionPositional
parametersRecursionRedirecting
stdin
of a functionreturnMultiple return values from
a function,
example script
Returning an array from
a functionReturn
range limits, workaroundsShift
arguments passed to a functionUnusual function
names* * *Games and amusements
AnagramsAnagrams, againBingo Number GeneratorCrossword puzzle
solverCrypto-QuotesDealing a deck of cardsFifteen PuzzleHorse raceKnight's TourLife
gameMagic SquaresMusic-playing
scriptNimPachinkoPerquackeyPetals Around the RosePodcastingPoemSpeech
generationTowers of HanoiGraphic
versionAlternate graphic
versiongetopt,
external command for parsing script
command-line arguments
Emulated
in a scriptgetopts,
Bash builtin for parsing script
command-line arguments
$OPTIND /
$OPTARGGlobal
variableGlobbing,
filename expansion
Handling
filenames correctlyWild
cardsWill not match
dot filesGolden Ratio
(Phi) -ge ,
greater-than or equal
integer comparison test -gt ,
greater-than integer
comparison testgroff,
text markup and formatting languageGronsfeld cipher$GROUPS,
Groups user belongs togzip, compression utility* * *Hashing, creating lookup keys
in a table
Example
scripthead, echo
to stdout lines at the beginning of a text
filehelp, gives usage summary of
a Bash builtinHere
documents
Anonymous
here documents, using :Commenting out
blocks of codeSelf-documenting
scriptsbc in a here
documentcat
scriptsCommand
substitutionex
scriptsFunction,
supplying input toHere
stringsCalculating the Golden
RatioPrepending textAs the stdin of a
loopUsing
readLimit
string! as a
limit stringClosing limit
string may not be indentedDash option
to limit string,
Literal
text output,
for generating program codeParameter
substitutionDisabling
parameter substitutionPassing
parametersTemporary
filesUsing
vi non-interactivelyHistory commands$HOME,
user's home directoryHomework assignment solver$HOSTNAME,
system host name* * *$Id
parameter, in rcs (Revision Control
System)if [ condition ]; then ...
test construct
if-grep,
if and grep
in combinationFixup
for if-grep test$IFS,
Internal field separator variable
Defaults to
whitespaceInteger comparison
operatorsin,
keyword preceding
[list] in a for
loopInitialization table,
/etc/inittabInline group,
i.e., code blockInteractive script, test forI/O redirectionIndirect referencing of variables
New notation, introduced
in version 2 of Bash ( example script)iptables,
packet filtering and firewall utility
Usage
exampleExample
scriptIteration* * *Job IDs, tablejot,
Emit a sequence of integers. Equivalent to seq.
Random sequence
generationJust another Bash hacker!* * *Keywords
error,
if missingkill,
terminate a process by process ID
Options (,
)killall,
terminate a process by namekillall
script in /etc/rc.d/init.d* * *lastpipe shell
option -le ,
less-than or equal
integer comparison testlet,
setting and carrying out arithmetic operations on variables
C-style
increment and decrement
operatorsLimit string,
in a here document$LINENO,
variable indicating the line number where
it appears in a scriptLink, file
(using ln command)
Invoking script with multiple names,
using lnsymbolic
links, ln -s List constructs
And
listOr
listLocal variables
and recursionLocalizationLogical operators
(&&, ||,
etc.)Logout file,
the ~/.bash_logout fileLoopback device,
mounting a file on a block
deviceLoops
break
loop control commandcontinue loop
control commandC-style
loop within double
parenthesesfor loopwhile loopdo (keyword),
begins execution of commands within a loopdone (keyword),
terminates a loopfor
loopsforargin[list];
doCommand
substitution to generate
[list]Filename expansion
in [list]Multiple parameters
in each [list] elementOmitting
[list], defaults to
positional parametersParameterizing
[list]Redirectionin,
(keyword) preceding [list] in a
for loopNested
loopsRunning a
loop in the background,
script exampleSemicolon required, when do is on first line
of loopfor
loopwhile
loopuntil loopuntil [ condition-is-true ]; dowhile
loopwhile [ condition ]; doFunction call
inside test bracketsMultiple conditionsOmitting test
bracketsRedirectionwhile read constructWhich type of loop to
useLoopback devices
In /dev directoryMounting an ISO image -lt ,
less-than integer
comparison test* * *m4, macro processing language$MACHTYPE,
Machine typeMagic number,
marker at the head of a file indicating the file typeMakefile,
file containing the list of dependencies used by make commandman, manual
page (lookup)
Man page
editor (script)mapfile builtin,
loads an array with a text fileMath commandsMeta-meaningMorse code training scriptModulo, arithmetic
remainder operator
Application: Generating
prime numbersMortgage calculations,
example script* * *-n
String not
null testNamed pipe, a temporary
FIFO buffer
Example
scriptnc, netcat,
a network toolkit for TCP and UDP ports-ne,
not-equal-to integer comparison testNegation operator,
!, reverses the sense of a testnetstat, Network
statisticsNetwork programmingnl, a filter to number lines of
textNoclobber,
option to Bash to prevent overwriting
of filesNOT logical
operator, !null variable
assignment, avoiding* * *-o
Logical OR
compound comparison testObfuscation
Colon
as function nameHomework assignmentJust another Bash
hacker!octal, base-8 numbersod, octal
dump$OLDPWD
Previous working directoryopenssl encryption
utilityOperator
Definition
ofPrecedenceOptions,
passed to shell or script on command line or by set commandOr
listOr logical
operator, ||* * *Parameter
substitution
${parameter+alt_value}${parameter:+alt_value}Alternate value
of parameter, if set${parameter-default}${parameter:-default}${parameter=default}${parameter:=default}Default
parameters${!varprefix*}${!varprefix@}Parameter
name match${parameter?err_msg}Parameter-unset message${parameter}Value of
parameterCase modification
(version 4+ of
Bash).Script
exampleTable
of parameter
substitutionParent / child process
problem, a child process cannot
export variables to a parent processParentheses
Command
groupEnclose group
of Extended Regular
ExpressionsDouble parentheses,
in arithmetic expansion$PATH,
the path (location of system
binaries)
Appending directories to $PATH
using the +=
operator.Pathname,
a filename that incorporates the complete
path of a given file.
Parsing
pathnamesPerl, programming language
Combined in the
same file with a Bash scriptEmbedded in a
Bash scriptPerquackey-type
anagramming game (Quackey script)Petals Around the
RosePID,
Process ID, an identification
number assigned to a running process.Pipe, | ,
a device for passing the output of a command to another command
or to the shell
Avoiding
unnecessary commands in a
pipeComments embedded
withinExit status
of a pipePipefail,
set -o pipefail
option to indicate exit status
within a pipe$PIPESTATUS,
exit status of last executed
pipePiping output of a command
to a scriptRedirecting
stdin, rather than using
cat in a
pipePitfalls
-
(dash) is not redirection
operator//
(double forward slash), behavior of cd command toward#!/bin/sh
script header disables extended Bash
featuresAbuse of
catCGI
programming, using scripts forClosing limit string
in a here document,
indentingDOS-type newlines
(\r\n) crash a scriptDouble-quoting
the backslash (\)
charactereval, risk of
usingExecute permission
lacking for commands within a scriptExit status,
anomalous
Exit status
of arithmetic expression not
equivalent to an error codeExport
problem, child process
to parent processExtended
Bash features not
availableFailing to
quote variables
within test bracketsGNU
command set, in cross-platform scriptslet misuse:
attempting to set string variables
Multiple echo
statements in a function whose
output is capturednull
variable assignmentNumerical and string
comparison operators not
equivalent=
and -eqnot
interchangeableOmitting
terminal semicolon,
in a curly-bracketed code blockPipingecho
to a loopecho
to read (however, this problem
can be circumvented)tail
to grepPreserving whitespace
within a variable, unintended
consequencessuid
commands inside a scriptUndocumented
Bash features,
danger ofUpdates to Bash
breaking older
scriptsUninitialized
variablesVariable names,
inappropriateVariables in a
subshell, scope
limitedSubshell in while-read
loopWhitespace,
misuse ofPointersand file descriptorsand functionsand indirect
referencesand
variablesPortability issues
in shell scripting
Setting path
and umaskA test suite
script (Bash versus classic Bourne
shell)Using whatisPositional parameters
$@,
as separate words$*,
as a single wordin
functionsPOSIX,
Portable Operating System Interface /
UNIX
option1003.2 standardCharacter
classes$PPID,
process ID of parent processPrecedence, operatorPrepending
lines at head of a file, script
examplePrime numbers
Generating primes
using the factor
commandGenerating primes
using the modulo
operatorSieve of Eratosthenes, example scriptprintf,
formatted print command/proc directory
Running processes,
files describingWriting to
files in /proc,
warningProcess
Child
processParent
processProcess
ID (PID)Process substitution
To compare contents of
directoriesTo supply stdin of a
commandTemplatewhile-read loop
without a
subshellProgrammable completion
(tab expansion)Prompt
$PS1, Main
prompt, seen at command
line$PS2,
Secondary promptPseudo-code,
as problem-solving method$PWD,
Current working directory* * *Quackey, a
Perquackey-type anagramming game (script)Question mark, ? Character
match in an Extended Regular
ExpressionSingle-character
wild card,
in globbingIn a
C-style
Trinary (ternary) operatorQuoting
Character
stringVariableswithin test
bracketsWhitespace,
using quoting to
preserve* * *Random numbers
/dev/urandomrand(),
random function in awk$RANDOM, Bash
function that returns a pseudorandom integerRandom sequence
generation, using date
commandRandom sequence
generation, using jotRandom string,
generatingRaspberry Pi (single-board computer)
Script for preparing a bootable SD card
rcsread, set value of a
variable from stdinDetecting
arrow keysOptionsPiping
output of cat
to readPrepending
text
Problems piping echo
to readRedirection from a
file to read$REPLY,
default read variableTimed
inputwhile read
constructreadline libraryRecursion
Demonstration ofFactorialFibonacci
sequenceLocal
variablesScript
calling itself recursivelyTowers
of HanoiRedirection
Code
blocksexec
<filename,to reassign
file descriptorsIntroductory-level
explanation of I/O
redirection
Open a file for both
reading and writing<>filenameread
input redirected from a filestderr to
stdout2>&1 stdin /
stdout,
using - stdinof a
functionstdout to a file> ... >>stdout to
file descriptorj>&j
file descriptori to
file descriptorji>&j stdout
of a command to stderr>&2stdoutandstderr
of a command to a file&>
tee, redirect to a file
output of command(s) partway through a pipeReference Cards
Miscellaneous
constructsParameter
substitution/expansionSpecial shell
variablesString
operationsTest operatorsBinary comparisonFilesRegular
Expressions^ (caret)
Beginning-of-line
$ (dollar sign)
Anchor. (dot)
Match single
character* (asterisk)
Any number of
characters[ ] (brackets) Enclose character set
to match\ (backslash) Escape, interpret following
character literally\< ... \>
(angle brackets, escaped)
Word boundaryExtended
REs+ Character
match\{ \} Escaped
curly brackets[: :] POSIX character classes$REPLY,
Default value associated with read
commandRestricted shell,
shell (or script) with certain commands disabledreturn,
command that terminates a functionrun-parts
Running scripts
in sequence, without user intervention* * *Scope of a variable,
definitionScript options,
set at command lineScripting routines,
library of useful definitions and functionsSecondary prompt,
$PS2Security issues
nmap,
network mapper
/ port scannersudosuid
commands inside a scriptViruses,
trojans, and worms in scriptsWriting
secure scriptssed,
pattern-based programming language
Table,
basic operatorsTable,
examples of operatorsselect,
construct for menu building
in
list omitted
SemaphoreSemicolon required,
when do
keyword is on first line of loop
When
terminating curly-bracketed
code blockseq,
Emit a sequence of integers. Equivalent to jot.set,
Change value of internal script variables
set -u,
Abort script with error message if attempting to use
an undeclared variable.Shell script,
definition ofShell wrapper,
script embedding a command or utilityshift, reassigning
positional parameters$SHLVL,
shell level, depth to which the shell
(or script) is nestedshopt,
change shell optionsSignal,
a message sent to a processSimulations
Brownian
motionGalton
boardHorseraceLife,
game ofPI,
approximating by firing cannonballsPushdown
stackSingle quotes
(' ... ') strong quotingSocket, a communication
node associated with an I/O portSorting
Bubble
sortInsertion
sortsource,
execute a script or, within a script, import a file
Passing positional
parametersSpam, dealing with
Example
scriptExample
scriptExample
scriptExample
scriptSpecial charactersStack
DefinitionEmulating a push-down stack,
example scriptStandard Deviation, example scriptStartup files, Bashstdin
and stdoutStopwatch,
example scriptStrings
=~
String match operator
ComparisonLength${#string}ManipulationManipulation,
using awkNull
string, testing forProtecting strings
from expansion and/or reinterpretation,
script exampleUnprotecting
strings,
script examplestrchr(), equivalent ofstrlen(), equivalent ofstrings command,
find printable strings in a binary or data fileSubstring extraction${string:position}${string:position:length}Using
exprSubstring
index (numerical position in
string)Substring
matching, using
exprSubstring
removal${var#Pattern}${var##Pattern}${var%Pattern}${var%%Pattern}Substring replacement${string/substring/replacement}${string//substring/replacement}${string/#substring/replacement}${string/%substring/replacement}
Script
exampleTable
of string/substring manipulation and
extraction operatorsStrong quoting
' ... 'Stylesheet
for writing scriptsSubshell
Command list within
parenthesesVariables,
$BASH_SUBSHELL and
$SHLVLVariables in a subshellscope
limited, but ... ... can be accessed outside
the subshell?
su Substitute
user, log on as a different user or as
rootsuid (set user
id) file flag
suid
commands inside a script, not advisableSymbolic linksSwapfiles* * *Tab completionTable lookup, script
exampletail, echo
to stdout lines at the (tail) end of a text
filetar, archiving utilitytee, redirect to a file
output of command(s) partway through a pipeTerminals
setserialsettermsttytputwalltest command
Bash
builtinexternal
command, /usr/bin/test
(equivalent to /usr/bin/[)Test constructsTest operators
-a
Logical AND
compound comparison-e
File exists-eq
is-equal-to (integer
comparison)-f
File is a regular
file-ge
greater-than or equal
(integer comparison)-gt
greater-than (integer
comparison)-le
less-than or equal
(integer comparison)-lt
less-than
(integer comparison)-n
not-zero-length
(string comparison)-ne
not-equal-to
(integer comparison)-o
Logical OR
compound comparison-u suid
flag set, file test-z
is-zero-length
(string comparison)=
is-equal-to
(string comparison)==
is-equal-to
(string comparison)<
less-than
(string comparison)<
less-than,
(integer comparison, within
double parentheses)
<=
less-than-or-equal,
(integer comparison, within
double parentheses)
>
greater-than
(string comparison)>
greater-than,
(integer comparison, within
double parentheses)>=
greater-than-or-equal,
(integer comparison, within
double parentheses)
||
Logical OR &&
Logical AND!
Negation operator, inverts exit status of a
test!=
not-equal-to
(string comparison)Tables of test
operatorsBinary comparisonFileText and text file
processingTime / DateTimed input
Using
read -tUsing
sttyUsing
timing loopUsing
$TMOUTTips and hints
for Bash scripts
Array, as
return value from
a functionAssociative array
more efficient
than a numerically-indexed arrayCapturing
the return value of a function, using
echoCGI
programming, using scripts forComment blocksUsing anonymous
here documentsUsing if-then
constructsComment headers,
special purposeC-style syntax ,
for manipulating variablesDouble-spacing a text
fileFilenames prefixed with a dash,
removingFilter,
feeding output back to same
filterFunction
return value
workaroundsif-grep
test fixupLibrary
of useful definitions and
functionsnull
variable assignment, avoidingPassing
an array to a
function$PATH,
appending to, using the
+= operator.Prepending
lines at head of a fileProgress
bar templatePseudo-codercsRedirecting a test
to /dev/null to suppress outputRunning scripts in
sequence without user intervention, using run-partsScript as embedded
commandScript portabilitySetting path
and umaskUsing whatisSetting script variable
to a block of embedded sed or
awk codeSpeeding up script execution by disabling unicodeSubshell variable,
accessing outside the subshell
Testing a variable
to see if it contains only digitsTesting whether
a command exists, using typeTracking script
usagewhile-read loop
without a
subshellWidgets, invoking from a
script$TMOUT,
Timeout intervalToken, a symbol that may
expand to a keyword or
commandtput, terminal-control
commandtr, character translation filter
DOS to Unix text file
conversionOptionsSoundex, example
scriptVariantsTrap,
specifying an action upon receipt of a signalTrinary (ternary) operator,
C-style,
var>10?88:99in
double-parentheses
constructin let
constructtrue,
returns successful (0) exit statustypeset builtin
options* * *$UID,
User ID numberunalias,
to remove an aliasuname,
output system informationUnicode, encoding standard
for representing letters and symbols
Disabling unicode
to optimize scriptUninitialized variables uniq,
filter to remove duplicate lines from a sorted fileunset,
delete a shell variableuntil loopuntil [ condition-is-true ]; do* * *VariablesArray operations on
AssignmentScript
exampleScript
exampleScript
exampleBash
internal variablesBlock of sed or
awk code, setting a variable
toC-style
increment/decrement/trinary operations
Change value of internal script variables
using setdeclare,
to modify the properties of variablesDeleting a shell variable
using unsetEnvironmentalExpansion / Substring
replacement operatorsIndirect
referencingeval variable1=\$$variable2Newer notation${!variable}IntegerInteger / string (variables are
untyped)Length${#var}LvalueManipulating and
expandingName
and value of a variable,
distinguishing betweenNull
string, testing forNull
variable assignment, avoidingQuotingwithin test
bracketsto preserve
whitespacervalueSetting to null
valueIn
subshell
not visible to parent shellTesting a variable
if it contains only digitsTyping,
restricting the properties of a variableUndeclared,
error messageUninitialized
Unquoted
variable,
splittingUnsettingUntyped* * *wait,
suspend script execution
To remedy
script hangWeak quoting
" ... "while loopwhile [ condition ]; doC-style syntax
Calling a
function within
test bracketsMultiple
conditionsOmitting
test bracketswhile read
construct
Avoiding a
subshellWhitespace,
spaces, tabs, and newline characters
$IFS defaults
toInappropriate use
ofPreceding closing
limit string in a here
document, errorPreceding script
commentsQuoting,
to preserve whitespace within strings
or variables[:space:],
POSIX character classwho, information about logged on users
wwhoamilognameWidgetsWild card characters
Asterisk
*In
[list] constructs
Question mark
?Will not match
dot filesWord splitting
DefinitionResulting from command
substitutionWrapper, shell* * *xargs,
Filter for grouping arguments
Curly brackets
Limiting arguments passedOptionsProcesses arguments one at a time
Whitespace, handling* * *yes
Emulation* * *-z
String is
nullZombie,
a process that has terminated, but not yet been killed by its
parent