Show Menu
Cheatography

Bash Cheat-Sheet Cheat Sheet (DRAFT) by

Shell Variables, Substitutions/Expansions, Redirections, etc.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Shell Variables

$0
Name of script
$1 - $10
Positional parameters #1 - #10
$#
Number of positional parameters
\"\$­*"
All parameters (single word)
"­$@"
All parameters (separate strings)
${#*}
${#@}
Number of parameters
$?
Return value
$$
Process ID (PID)
$-
Flags (using
set
)
$_
Last argument of previous command
$!
PID of last job run in background
* Must be quoted, otherwise it defaults to "­$@".

Substi­tut­ion­/Ex­pansion

${VAR}
Value of
VAR
${VAR-­word}
If VAR not set,
use
­word
${VAR:­-­word}
If VAR not set
or null, use
­word
${VAR:=­word}
${VAR=word}
Assign default value.
(position./spec.param. may not be assigned)
${VAR:?­ERR_MSG}
${VAR?­ERR_MSG}
Display Error Message if null or unset
${VAR:­+­word}
Use Alternate: null/unset - nothing, else -
word
${VAR:­o­f­fs­et}
Substring
${VAR:o­ffs­et:­len­gth}
Substring with size
length
${!VAR[@]}
${!VAR[*]}
List Array Keys
${#VAR}
Parameter length
${VAR#­m­atch}
Remove prefix
${VAR#­#­m­at­ch}
Remove prefix (longest)
${VAR%­m­atch}
Remove suffix
${VAR%­%­m­at­ch}
Remove suffix (longest)
${VAR/­p­a­tt­­ern­­/str}
Replace first match of
pattern
with
str
${VAR/­p­a­tt­­ern­­/str}
Replace all match of
pattern
with
str
${VAR^­p­a­tt­ern}
Uppercase match
${VAR^­^­p­at­­tern}
Uppercase all
${VAR,­p­a­tt­ern}
Lowercase match
${VAR,­,­p­at­­tern}
Lowercase all
${!VAR*}
${!VAR@}
Match all vars begginning with
VAR

HISTORY MANIPU­LATION

!!
Last command
!?foo
Last command containing
foo
^foo^bar^
Last command containing
foo
, but substitute
bar
!!:0
Last command word
!!:^
Last command's first argument
!$
Last command's last argument
!!:*
Last command's arguments
!!:x-y
Arguments x to y of last command
C-s
search forwards in history
C-r
search backwards in history
C - Control Key
 

DIRECT­ORIES

~-
Previous working directory
pushd tmp
Push tmp && cd tmp
popd
Pop && cd

GLOBBING

ls a[b-dx]e
Globs abe, ace, ade, axe
ls a\{c,bl\}e
Globs ace, able
$(ls)
`ls`
(but nestable!)

Redire­ctions

cmd > file
Redirect the standard output (stdout) of
cmd
to a file.
cmd 1> file
cmd 2> file
cmd >> file
cmd 2>> file
cmd &> file
cmd > file 2>&1
cmd > /dev/null
cmd 2> /dev/null
cmd &> /dev/null
cmd < file
cmd << EOL
foo
bar
EOL
cmd <<- EOL
<tab>foo
<tab><tab>bar
EOL
cmd <<< "­str­ing­"
exec 2> file
exec 3< file
exec 3> file
exec 3<> file
exec 3>&-
exec 4>&3
exec 4>&3-
echo "­foo­" >&3
cat <&3
(cmd1; cmd2) > file
{ cmd1; cmd2; } > file
exec 3<> /dev/t­cp/­hos­t/port
exec 3<> /dev/u­dp/­hos­t/port
cmd <(cmd1)
cmd < <(cmd1)
cmd <(cmd1) <(cmd2)
cmd1 >(cmd2)
cmd1 | cmd2
cmd1 |& cmd2
cmd | tee file
exec {filew­}> file
cmd 3>&1 1>&2 2>&3
cmd > >(cmd1) 2> >(cmd2)
cmd1 | cmd2 | cmd3 | cmd4
echo ${PIPE­STA­TUS[@]}