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 ...
$0
is the name of the script itself,$1
is the first argument,$2
the second,$3
the 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 > file
Sends standard output to <file>
command 2> file
Sends error output to <file>
command 2>&1
Sends error output to standard output command > file 2>&1
Sends standard output and the error output to a file command &> file
Sends standard output and the error output to a file command 2>&1 > file
Sends error output to standard input and the standard input to a file -
Append with
>>
Command Description command >> file
Appends standard output to a file command 2>> file
Appends error output to a file command >> file 2>&1
Appends standard output and error output to a file command &>> file
Appends standard output and error output to a file command 2>&1 >> file
Sends error output to standard input and appends standard input to a file -
Redirect with
<
Command Description command < $file
Sends file contents to standard input command << $delimiter
Sends a command or interactive program with a list defined by a delimiter; this is known as a here-document (heredoc) command <<< $word
Sends a command with word; this is known as a here-string -
Resources
Pipeline
-
|
cmd1 | cmd2
cmd1 -> stdout -> stdin -> cmd2
The output of each command
in the pipeline is connected via apipe
to theinput
ofthe next command
. That is,each command
reads 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
’sstdin
through thepipe
; it is shorthand for2>&1 |
. This implicit redirection of thestderr
to thestdout
is 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>&1
Target file must exist before running the command.
Shell Scripting
-
Variable
-
Assignment
space
is forbidden around=
-
Substitution
${VARIABLE}
or$VARIABLE
- Enclosing a
referenced value
indouble quotes
(" ... ")
doesn't affectvariable substitution
. - Using
single quotes
(' ... ')
causes the variable name to be used literally, andno substitution
will 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 . . .
.$0
is thename of the script
itself,$1
is thefirst argument
,$2
the 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 test
if test <CONDITION>
is equivalent toif [ <CONDITION> ]
-
if
(opens in a new tab) (condition test)- An
if/then
construct tests whether theexit status
of a list of commands is0
(since0
means "success" byUNIX
convention), 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 substitution
invokes asubshell
.- Command output is returned
Command substitution
permits nesting
-
Arithmetic Expansion (opens in a new tab)
-
((EXPRESSION))
(Bash
)- similar to a
void
function invocation, withno return value
but anexit status
- If the
expression
evaluates as0
, it returns anexit status
of1
, or "false
". Anon-zero
expression
returns anexit status
of0
, or "true
".let
works in the same way.
- similar to a
-
let
commandlet 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
type
of 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 command
will run inbackground
.The
second command
will run inforeground
.command1 & command2
-
conditional execution
The
second command
will only run when thefirst command
return an exit status of0
.cd "$SOMEWHERE" && ./do_something
-
-
Bash builtins
- Generally, a
Bash
builtin
does notfork
a subprocess when it executes within a script. - On the other hand, an
external system command or filter
in a script usually willfork
a 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
return
to exit script
-
execute
- Run the script in a new shell
- Use
exit
to exit script
Loop through all files and directories under the current directory
-
for file in *; do echo "$file"; done
Files and directories except those starting with
.
-
for file in .*; do echo "$file"; done
Files 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
000005
Get 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 $@
}