Variables
Local variables
Environment variables
- Each process has an "environment", that is, a group of variables that the process may reference.
- Every time a shell starts, it creates shell variables that correspond to its own environmental variables.
- Updating or adding new environmental variables causes the shell to update its environment, and all the shell's child processes (the commands it executes) inherit this environment.
- A script can export variables only to child processes, that is, only to commands or processes which that particular script initiates.
Positional parameters
- Arguments passed to the script from the command line:
$0, $1, $2, $3 ... $0is the name of the script itself,$1is the first argument,$2the second,$3the third, and so forth. After$9, the arguments must be enclosed in brackets, for example,${10},${11},${12}.- The special variables
$*and$@denote all the positional parameters.
Redirection

-
Redirection with
>Command Description command > fileSends standard output to <file>command 2> fileSends error output to <file>command 2>&1Sends error output to standard output command > file 2>&1Sends standard output and the error output to a file command &> fileSends standard output and the error output to a file command 2>&1 > fileSends error output to standard input and the standard input to a file -
Append with
>>Command Description command >> fileAppends standard output to a file command 2>> fileAppends error output to a file command >> file 2>&1Appends standard output and error output to a file command &>> fileAppends standard output and error output to a file command 2>&1 >> fileSends error output to standard input and appends standard input to a file -
Redirect with
<Command Description command < $fileSends file contents to standard input command << $delimiterSends a command or interactive program with a list defined by a delimiter; this is known as a here-document (heredoc) command <<< $wordSends a command with word; this is known as a here-string -
Resources
Pipeline

-
|cmd1 | cmd2cmd1 -> stdout -> stdin -> cmd2
The output of each commandin the pipeline is connected via apipeto theinputofthe next command. That is,each commandreads the previous command’s output. This connection is performed before any redirections specified bycommand1. -
|&cmd1 -> (stdout & stderr) -> stdin -> cmd2
If
|&is used,command1’sstderr, in addition to itsstdout, is connected tocommand2’sstdinthrough thepipe; it is shorthand for2>&1 |. This implicit redirection of thestderrto thestdoutis performed after any redirections specified bycommand1. -
Resources
Pipeline - Cheatsheet
When you don't want to see the output in the terminal
>> /dev/null
Redirect both stdout and stderr to a file
-
<command> >>file.txt 2>&1Target file must exist before running the command.
Shell Scripting
-
Variable
-
Assignment
spaceis forbidden around=
-
Substitution
${VARIABLE}or$VARIABLE- Enclosing a
referenced valueindouble quotes(" ... ")doesn't affectvariable substitution. - Using
single quotes(' ... ')causes the variable name to be used literally, andno substitutionwill take place. - Bash Reference Manual - 3.5.3 Shell Parameter Expansion (opens in a new tab)
-
Local variable (opens in a new tab) (
Bash)- Only visible within the scope
local a=1
-
Positional parameters(opens in a new tab)- Arguments passed to the script from the command line:
$0, $1, $2, $3 . . ..$0is thename of the scriptitself,$1is thefirst argument,$2the second, and so forth. - The special variables
$*and$@denote all the positional parameters.
- Arguments passed to the script from the command line:
-
-
Construct
-
Test Constructs (opens in a new tab)
man testif test <CONDITION>is equivalent toif [ <CONDITION> ] -
if(opens in a new tab) (condition test)- An
if/thenconstruct tests whether theexit statusof a list of commands is0(since0means "success" byUNIXconvention), and if so, executes one or more commands.
- An
-
-
Exit status(opens in a new tab)Denoted by
$?, and can be checked withecho $? -
Command substitution (opens in a new tab)
listing=$(ls *.txt)Command substitutioninvokes asubshell.- Command output is returned
Command substitutionpermits nesting
-
Arithmetic Expansion (opens in a new tab)
-
((EXPRESSION))(Bash)- similar to a
voidfunction invocation, withno return valuebut anexit status - If the
expressionevaluates as0, it returns anexit statusof1, or "false". Anon-zeroexpressionreturns anexit statusof0, or "true".letworks in the same way.
- similar to a
-
letcommandlet a++- Same as
((EXPRESSION)), returning anexit status
-
$((EXPRESSION))(POSIX)- similar to a function invocation with
return value
- similar to a function invocation with
-
Bash features
-
[[ ... ]](opens in a new tab) Extended test construct and regex matching -
Check
typeof a single wordtype -a <WORD>$ type -a ls ls is an alias for ls --color=tty ls is /usr/bin/ls ls is /bin/ls -
Command execution (opens in a new tab)
-
batch
Commands run consecutively, separated by
;.command1; command2 -
concurrent
Commands run concurrently, separated by
&.The
first commandwill run inbackground.The
second commandwill run inforeground.command1 & command2 -
conditional execution
The
second commandwill only run when thefirst commandreturn an exit status of0.cd "$SOMEWHERE" && ./do_something
-
-
Bash builtins
- Generally, a
Bashbuiltindoes notforka subprocess when it executes within a script. - On the other hand, an
external system command or filterin a script usually willforka subprocess. - Advanced Bash-Scripting Guide - Chapter 15. Internal Commands and Builtins (opens in a new tab)
- Generally, a
-
Heredoc
Shell Scripting - Cheatsheet
source vs execute a script
-
source- Run the script in the current shell
- Use
returnto exit script
-
execute- Run the script in a new shell
- Use
exitto exit script
Loop through all files and directories under the current directory
-
for file in *; do echo "$file"; doneFiles and directories except those starting with
. -
for file in .*; do echo "$file"; doneFiles and directories starting with
.only
Cheatsheet
Generate a sequence of numbers
for i in $(seq -f "%06g" 1 5); do echo $i; done# Example
> for i in $(seq -f "%06g" 1 5); do echo $i; done
000001
000002
000003
000004
000005Get the function arguments from the second to the last
Use shift to remove the first argument, and then $@ now contains the arguments from the second to the last.
example_function() {
shift
echo $@
}