28 KiB
title, description, summary, draft, tags, author, showToc
| title | description | summary | draft | tags | author | showToc |
|---|---|---|---|---|---|---|
| Shell Scripting [BASH] | true | TrudeEH | true |
Strings
""Defines a string which supports substitutions ($and\, for example).''Defines a string, but preserves its actual value (substitutions are treated as regular characters).- ANSI Escape Sequences apply when using
"".
Comments
# comment
Commands
A shell command consists of the command itself, followed by its arguments.
command "arg1" "arg2"
If the first word of a command is a reserved word, bash handles the command, otherwise, it searches for an executable on the system's $PATH, a list of directories where a binary could be located.
Reserved Words
if |
then |
elif |
else |
fi |
time |
for |
in |
until |
while |
do |
done |
case |
esac |
coproc |
select |
function |
|
{ |
} |
[[ |
]] |
! |
List of Commands
command1 ; command2Execute command2 after command1, sequentially.command1 &Execute command1 asynchronously in a subshell.command1 && command2AND: Only execute command2 if command1 returns 0 (success).command1 || command2OR: Only execute command2 if command1 returns a non-zero exit value (failure).
Loops
until
until test-commands; do
...
done
Execute the code in ... for as long as test-commands return non-zero.
while
while test-commands; do
...
done
Execute ... for as long as test-commands return 0.
for
Expand words and execute ... for each member in the resultant list, with name bound to the current member.
Iterate through List
for item in list; do
echo $item
done
C-like Loop
for (( i=1; i<=10; i++ )); do
echo "Loop number:" $i
done
Infinite Loop
for (( ; ; )); do
echo "Press Ctrl+C to stop..."
done
Conditional Constructs
if
if test-commands; then
...
elif more-test-commands; then
...
else
...
fi
Execute the first ... if test-commands returns 0, and evaluate the next condition otherwise. This process repeats until else is found, or one of the tests evaluates to a 0.
Once any ... executes, the remaining if construct is skipped.
case
case word in
p1 | p2 | p3) ... ;;
p4 | p5 )
...
;;
*) ... ;;
esac
Execute the ... corresponding to the first pattern (pX) that matches the word.
The | operator separates multiple patterns, and each clause can end with ;;, ;& or ;;&. It's common to use * as the default case, since the pattern will always match.
Using ;& instead of ;; would cause the next ... to be executed as well, and ;;& would test the next clause, instead of immediately exiting.
select
PS3="Enter a number: "
select option in entry1 entry2 entry3 entry4 entry5
do
echo "Selected character: $option"
echo "Selected number: $REPLY"
done
The select command generates a menu, displaying each entryX in a list. The user is then prompted to select an option (in this case, a number from 1-5), and the resultant $option and $REPLY are then provided as variables.
Output:
1) entry1
2) entry2
3) entry3
4) entry4
5) entry5
Enter a number:
((...))
The arithmetic expression is evaluated according to the rules described below (see Shell Arithmetic TODO link to shell arithmetic).
[[...]]
Return a status of 0 or 1 depending on the evaluation of the conditional expression expression. Expressions are composed of the primaries described below in Bash Conditional Expressions.
Combine Expressions
( expression )Returns the value of expression. (Can be used to override precedence).! expressionNOT an expression. (trueif expression isfalse).exp1 && exp2AND -trueif both expressions aretrue.exp1 || exp2OR -trueif either expressions aretrue.
Grouping Commands
Bash allows for commands to be grouped as a single unit. That way, if the group is redirected, the output of every command in the list is passed to a single stream.
( list )Create a subshell (variables created inside it can't be accessed outside).{ list; }No subshell is created.
Functions
fname() {
...
}
function fname {
...
}
A function can store a block of code (compound command), so it can be reused by calling its name:
fname
Any variables defined inside the function
Arguments
fname() {
echo $1 $2
}
fname "a" "b"
Scope
var1='A'
var2='B'
fname () {
local var1='C'
var2='D'
echo "var1: $var1, var2: $var2" # C, D
}
echo "$var1, var2: $var2" # A, B
fname # C, D
echo "var1: $var1, var2: $var2" # A, D
Defining a variable inside the function overwrites the global scope. To prevent this, use the local keyword.
return
fname() {
return 1;
}
fname
echo $? # 1
Use the return command to exit the function and return a value.
Variables (Parameters)
name="Trude"
echo $name # Trude
name+=" EH"
echo $name # Trude EH
echo ${name}
Variables can be of any type, and grow to any needed size.
Special Variables
$*Expands to every positional parameter:$1$2$3.$@Expands to every positional parameter, separated by spaces:"$1" "$2" "$3".$#Number of positional arguments.$?Exit status of last command / pipeline.$-Current option flags set byset, or by the shell itself.$$Process ID of the shell. In a subshell, it expands to the process ID of the parent shell.$!Process ID of the latest job placed into the background.$0Name of the shell or script.
Shell Expansions
Brace Expansion
echo a{d,c,b}e # ade ace abe
Tilde Expansion
~=$HOME~+=$PWD~-=$OLDPWD
Shell Parameter Expansion
${var}Braces are required if the variable is positional and over one digit, or if it is followed by a character that is not part of its name.${!var}Access the value ofvar, and checks if it is the name of another variable. If so, expands that variable. (Pointer)${var:-word}Ifvaris null or unset, use thewordvalue instead.${var:=word}Ifvaris null or unset, set its value toword. (Good for default values)${var:?word}Ifvaris null or unset,wordis written to the standard error, and the shell, if not interactive, exits.${var:+word}Use thewordvalue ifvaris not unset or null.${var:offset:length}Offsetvarand return the desired length. (Cut strings)${@:offset:length}Same as before, but with positional arguments.${!word*}Access the value of all variables whose names begin withword. Use@instead of*to separate the result to separate words.${!var[*]}Expand all indices (keys) in an array. (Not values;@also works).${#var}Length of a variable's value.${var#word}Ifwordis found invar, return the remaining text after it appears for the first time. Otherwise, print the entire variable.${var##word}Ifwordis found invar, return the remaining text after it appears for the last time. Otherwise, print the entire variable.${var%word}Ifwordis found invar, return the remaining text before it appears for the first time. Otherwise, print the entire variable.${var%%word}Ifwordis found invar, return the remaining text before it appears for the last time. Otherwise, print the entire variable.${var/pattern/word}Readvar's value, then replace the first occurrence ofpatternwithword.${var//pattern/word}Readvar's value, then replace all occurrences ofpatternwithword.${var/#pattern/word}Replacepatternwithword, only ifpatternis at the beginning ofvar.${var/%pattern/word}Replacepatternwithword, only ifpatternis at the end ofvar.${var^word}Convert the first character that matcheswordto uppercase.${var^^word}Convert all characters that matchwordto uppercase.${var,word}Convert the first character that matcheswordto lowercase.${var,,word}Convert all characters that matchwordto lowercase.${var@X}ReplaceXwith one of the following operators:UUppercase.uUppercase first character.LLowercase.QQuote in a format that can be reused as input.EExpand escape sequences.PExpand the value as if it was a prompt string.AGenerate the variable declaration command forvar.KOutput key-value pairs, suitable for generating the source array.aOutput the flags corresponding tovar's attributes.kSame asK, but separates keys and values using spaces, making it easier to loop through them.
Command Substitution
echo "$(command)"
echo "`command`"
Execute a command and substitute itself with the command's result.
Arithmetic Expansion
echo "$(( expression ))"
Performs an arithmetic expression and substitutes itself with the result.
Process Substitution
cat <(command) >(command)
cat <(cat /etc/hostname) >(gzip > output.gz)
The <() substitution executes the command asynchronously, stores the result in a temporary file (in /tmp/), and substitutes itself with the temporary file's path.
The >() substitution is also executed asynchronously, and creates a temporary file with the command's output, then passes it to the next program's input.
Neither
catnorgziparebashcommands ('builtins'), but external programs.
Pattern Matching
*Matches any string.?Matches any single character.[...]Matches any of the enclosed characters, and supports ranges. ([a-z])?(pattern-list)Matches zero or one of the given patterns.*(pattern-list)Matches zero or more occurrences of the given patterns.+(pattern-list)Matches one or more occurrences of the given patterns.@(pattern-list)Matches one of the given patterns.!(pattern-list)Matches anything except the given patterns.
Redirections
command > destRedirect the output of a command to a destination: A file, device, command, list, etc.command >> destAppend to the destination instead of overwriting.command < fileProvide a file as input.command 2> destRedirect the error output of a command.command &> destorcommand >& destRedirect both input and output.command 2>&1Redirect Standard Error to Standard Output.command > /dev/nullDiscard the output.
It is also possible to provide strings as input directly:
cat <<< "String!"
cat << EOF
Multi-line
string
EOF
Shell Builtin Commands
This section is an introduction to every command available in bash.
To learn more about some command, run help command.
Bourne Shell Commands
: argumentsDo nothing beyond expanding arguments and performing redirections.. fileRead and execute commands fromfile.breakExit from a loop. (Adding a number as an argument selects which enclosing loop to exit from.)cd directoryChange the current directory todirectory. Ifdirectoryis...->$HOME..-> Parent directory-->$OLDPWD
continueSkip to the next iteration of a loop. (Also supports loop number as an argument.)eval argumentsArguments are concatenated together and executed as a single command.exec commandReplaces the shell without creating a new process, and executes the command.exitExit the shell. (Optionally, add a return status.)export nameMake a variable available to child processes.exportcan also handle functions and assignment.getopts "optstring" varParse positional parameters (script arguments).hashList the full paths to executables cached by the shell (to accelerate future queries)pwdPrint the full pathname of the current directory.return valueExit a function and returnvalue. If no value is provided, returns the last exit status of the last command executed in the function.shift valueShift the positional parameters to the left byvalue. If no value is provided, shift by 1.testor[]Evaluate a condition and return 0 iftrue, or 1 iffalse:timesPrint the user and system times used by the shell and its children.trap "command" signalExecute a command, if one of the following signals are received: (TheSIGprefix is optional)SIGINTInterrupt signal (usually generated by pressing Ctrl+C).SIGTERMTermination signal (Request to terminate).SIGKILLKill signal (Forceful termination; Cannot be trapped).SIGQUITQuit signal.SIGUSR1andSIGUSR2User-defined signals.SIGCHLDChild process terminated.0orEXITExecutes when the shell exits.DEBUGExecutes before every simple command.RETURNExecutes each time a shell function or a script executed with the.orsourcebuiltins finishes executing.ERRExecutes whenever any pipeline, list, or command returns a non-zero exit status.
umaskDefines which permissions should be removed from newly created files.unsetRemove a variable or function name. (Use-fto remove the actual function definition)
Bash Commands
aliasPrints the list of aliases or defines new ones (withalias name=value).bindDisplays or sets key and function bindings for Readline.builtinExecutes a shell builtin command, bypassing any function with the same name.callerReturns context information of the current active subroutine call.commandExecutes a command, ignoring any shell function with the same name. (If the-voption is supplied, prints a description ofcommand.)declareDeclares variables with various attributes (typeset is a synonym).echoOutputs its arguments to the standard output.enableEnables or disables shell builtin commands.helpProvides helpful information about shell builtins.letEvaluates arithmetic expressions.localCreates a variable with a scope local to the function.logoutExits a login shell with an optional exit status.mapfileReads lines from input into an indexed array (readarray is a synonym).printfPrints formatted output to the standard output.readReads a line of input and splits it into words based on IFS.readarrayReads lines from input into an indexed array (synonym for mapfile).setSet or unset values of shell options and positional parametersshoptChange additional shell optional behavior.sourceExecutes commands from a file in the current shell environment.typeDescribes how the shell interprets a given command name.ulimitControls resource limits for processes created by the shell.unaliasRemoves defined aliases, with an option to remove all.
Shell Variables
Bourne Shell Variables
CDPATHSearch path directories for thecdcommand.HOMECurrent user's home directory, default forcd.IFSCharacters used to separate fields during word splitting.MAILFile/directory Bash checks for mail ifMAILPATHis unset.MAILPATHColon-separated list of files/directories to check for mail.OPTARGValue of the last option argument processed bygetopts.OPTINDIndex of the last option argument processed bygetopts.PATHColon-separated list of directories searched for commands.PS1Primary prompt string displayed interactively.PS2Secondary prompt string for continued commands.
Bash Variables
_Pathname of invoked shell/script, or last argument of previous command.BASHFull pathname used to execute the current Bash instance.BASHOPTSColon-separated list of enabled shell options (viashopt).BASHPIDProcess ID of the current Bash process (can differ from$$).BASH_ALIASESAssociative array mapping alias names to values.BASH_ARGCArray of parameter counts for each function/script in the call stack (requiresextdebug).BASH_ARGVArray of all parameters in the current call stack (requiresextdebug).BASH_ARGV0Name of the shell or script ($0); assigning to it also sets$0.BASH_CMDSAssociative array mapping hashed commands to their full paths.BASH_COMMANDCommand currently being executed or about to be executed.BASH_COMPATSets the shell's compatibility level (e.g., 4.2 or 42).BASH_ENVPath to a script read before executing a non-interactive script.BASH_EXECUTION_STRINGCommand argument passed via the-cinvocation option.BASH_LINENOArray of line numbers where functions inFUNCNAMEwere invoked.BASH_LOADABLES_PATHSearch path for dynamically loadable builtins (enable -f).BASH_REMATCHArray holding results from regex matching (=~) in[[...]].BASH_SOURCEArray of source filenames where functions inFUNCNAMEare defined.BASH_SUBSHELLIncremented for each subshell level; initial value is 0.BASH_VERSINFOReadonly array detailing the Bash version components.BASH_VERSIONString containing the full version number of Bash.BASH_XTRACEFDFile descriptor where trace output (set -x) is sent.CHILD_MAXMaximum number of exited child statuses the shell remembers.COLUMNSTerminal width, used byselectand set onSIGWINCHifcheckwinsizeis on.COMP_CWORDIndex inCOMP_WORDSarray of the word containing the cursor.COMP_LINEThe current command line being completed.COMP_POINTIndex of the cursor position within the current command line (COMP_LINE).COMP_TYPEInteger indicating the type of completion being attempted (TAB, ?, !, @, %).COMP_KEYThe key (or sequence) that invoked the completion function.COMP_WORDBREAKSCharacters Readline uses to delimit words for completion.COMP_WORDSArray of individual words in the current command line for completion.COMPREPLYArray where completion functions place possible matches.COPROCArray holding file descriptors for an unnamed coprocess.DIRSTACKArray containing the current directory stack (dirs).EMACSIf set totat startup, indicates running in Emacs, possibly disabling line editing.ENVScript executed when an interactive shell starts in POSIX mode.EPOCHREALTIMESeconds since the Unix Epoch, with microsecond precision (float).EPOCHSECONDSSeconds since the Unix Epoch (integer).EUIDNumeric effective user ID of the current user (readonly).EXECIGNOREPatterns of filenames to ignore duringPATHcommand lookup.FCEDITDefault editor used byfc -e.FIGNORESuffixes to ignore during filename completion.FUNCNAMEArray of function names currently on the execution call stack.FUNCNESTMaximum function nesting level; exceeding it aborts the command.GLOBIGNOREPatterns of filenames to ignore during pathname expansion (globbing).GROUPSArray containing the group IDs the current user belongs to.histcharsCharacters controlling history expansion (!), quick substitution (^), and comments (#).HISTCMDHistory number (index) of the current command in the history list.HISTCONTROLControls how commands are saved (ignorespace, ignoredups, ignoreboth, erasedups).HISTFILEFile where command history is saved (default~/.bash_history).HISTFILESIZEMaximum number of lines stored in the history file.HISTIGNOREPatterns matching command lines that should not be saved in history.HISTSIZEMaximum number of commands remembered in the current shell's history list.HISTTIMEFORMATstrftimeformat for displaying timestamps with history entries.HOSTFILEFile (like/etc/hosts) used for hostname completion.HOSTNAMEName of the current host.HOSTTYPEString describing the system architecture (e.g.,x86_64-linux-gnu).IGNOREEOFNumber of consecutive EOF characters (Ctrl+D) needed to exit an interactive shell.INPUTRCReadline initialization file (overrides~/.inputrc).INSIDE_EMACSSimilar toEMACS, indicates running within an Emacs shell buffer.LANGDefault locale category setting.LC_ALLOverridesLANGand all otherLC_locale settings.LC_COLLATELocale for string sorting and pattern matching ranges/classes.LC_CTYPELocale for character interpretation and classification in patterns.LC_MESSAGESLocale for translating double-quoted strings starting with$.LC_NUMERICLocale category for number formatting.LC_TIMELocale category for date and time formatting.LINENOCurrent line number within the script or function being executed.LINESTerminal height, used byselectand set onSIGWINCHifcheckwinsizeis on.MACHTYPESystem type string incpu-company-systemformat (similar toHOSTTYPE).MAILCHECKHow often (seconds) Bash checks for mail (default 60).MAPFILEDefault array variable used bymapfileif no name is given.OLDPWDPrevious working directory, set bycd.OPTERRIf set to 1,getoptsdisplays error messages.OSTYPEString describing the operating system (e.g.,linux-gnu).PIPESTATUSArray containing exit statuses of commands in the last foreground pipeline.POSIXLY_CORRECTEnables POSIX mode if set at startup or during execution.PPIDProcess ID of the shell's parent process (readonly).PROMPT_COMMANDCommand(s) executed just before displaying the primary prompt (PS1).PROMPT_DIRTRIMNumber of trailing directory components shown in\wand\Wprompts.PS0Prompt string displayed after reading a command but before executing it (interactive shells).PS3Prompt string used by theselectcommand.PS4Prompt string prefixed to commands echoed during execution tracing (set -x).PWDCurrent working directory, set bycd.RANDOMReturns a random integer between 0 and 32767; assigning seeds the generator.READLINE_ARGUMENTNumeric argument passed to a Readline command bound viabind -x.READLINE_LINEContents of the Readline line buffer (forbind -x).READLINE_MARKPosition of the mark (saved point) in the Readline buffer (forbind -x).READLINE_POINTPosition of the insertion point in the Readline buffer (forbind -x).REPLYDefault variable used byreadif no name is given.SECONDSNumber of seconds since the shell was started; assigning resets the counter.SHELLFull pathname to the current user's login shell.SHLVLShell nesting level, incremented for each new Bash instance started.SRANDOMReturns a 32-bit pseudo-random number (cannot be seeded).TIMEFORMATFormat string controlling output of thetimekeyword.TMOUTDefault timeout (seconds) forreadandselect; idle timeout for interactive shells.TMPDIRDirectory used for creating temporary files.UIDNumeric real user ID of the current user (readonly).
Parse Arguments
while getopts "ab:c" opt; do
case "$opt" in
a)
echo "Option -a was specified"
;;
b)
value="$OPTARG"
echo "Option -b was specified with value: $value"
;;
c)
echo "Option -c was specified"
;;
\?)
echo "Invalid option: -$OPTIND" >&2
exit 1
;;
:)
echo "Option -$OPTIND requires an argument." >&2
exit 1
;;
esac
done
shift $((OPTIND - 1))
echo "Remaining arguments: $@"
To enable silent error reporting, add
:at the beginning of thegetopts'optstring.
Bash Startup Files
| Shell Type | Files |
|---|---|
| Login | /etc/profile, ~/.bash_profile, ~/.bash_login, ~/.profile |
| Interactive | ~/.bashrc |
| Non-Interactive | $BASH_ENV |
sh |
/etc/profile, ~/.profile |
Detect if Running in Interactive Shell
case "$-" in
*i*) echo This shell is interactive ;;
*) echo This shell is not interactive ;;
esac
Conditional Expressions
Conditional Expressions are used by the [[]], [] and test commands.
-a fileTrue if file exists.-b fileTrue if file exists and is a block special file.-c fileTrue if file exists and is a character special file.-d fileTrue if file exists and is a directory.-e fileTrue if file exists. (Equivalent to-ain this context)-f fileTrue if file exists and is a regular file.-g fileTrue if file exists and its set-group-id bit is set.-h fileTrue if file exists and is a symbolic link.-k fileTrue if file exists and its "sticky" bit is set.-p fileTrue if file exists and is a named pipe (FIFO).-r fileTrue if file exists and is readable.-s fileTrue if file exists and has a size greater than zero.-t fdTrue if file descriptor fd is open and refers to a terminal.-u fileTrue if file exists and its set-user-id bit is set.-w fileTrue if file exists and is writable.-x fileTrue if file exists and is executable.-G fileTrue if file exists and is owned by the effective group id.-L fileTrue if file exists and is a symbolic link.-N fileTrue if file exists and has been modified since it was last read.-O fileTrue if file exists and is owned by the effective user id.-S fileTrue if file exists and is a socket.file1 -ef file2True if file1 and file2 refer to the same device and inode numbers.file1 -nt file2True if file1 is newer (according to modification date) than file2, or if file1 exists and file2 does not.file1 -ot file2True if file1 is older than file2, or if file2 exists and file1 does not.-o optnameTrue if the shell option optname is enabled.-v varnameTrue if the shell variable varname is set (has been assigned a value).-R varnameTrue if the shell variable varname is set and is a name reference.-z stringTrue if the length of string is zero.-n stringorstringTrue if the length of string is non-zero.string1 == string2orstring1 = string2True if the strings are equal. Use=for thetestcommand.string1 != string2True if the strings are not equal.string1 < string2True if string1 sorts before string2 lexicographically.string1 > string2True if string1 sorts after string2 lexicographically.arg1 OP arg2OPis one of '-eq', '-ne', '-lt', '-le', '-gt', or '-ge'. These arithmetic binary operators return true if arg1 is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to arg2, respectively.
Shell Arithmetic
Arithmetic is performed using (()), let and declare -i.
id++id--Variable post-increment and post-decrement++id--idVariable pre-increment and pre-decrement-+Unary minus and plus!~Logical and bitwise negation**Exponentiation*/%Multiplication, division, remainder+-Addition, subtraction<<>>Left and right bitwise shifts<=>=<>Comparison==!=Equality and inequality&Bitwise AND^Bitwise exclusive OR|Bitwise OR&&Logical AND||Logical ORexpr ? expr : exprConditional operator=*=/=%=+=-=<<=>>=&=^=|=Assignmentexpr1 , expr2Comma
Arrays
Indexed arrays
declare -a name
name[]=value
Associative arrays
declare -A name
name=(value1 value2 ...)
6.7 Arrays
https://www.gnu.org/software/bash/manual/bash.html#Bash-Features