8/31/2019 Bash scripting cheatsheet
[Link] Edit
Bash scripting cheatsheet
Proudly sponsored by
MongoDB Atlas is the most reliable cloud
database service available. Try now!
ethical ad by CodeFund
Example Variables St
#!/usr/bin/env bash NAME="John"
echo $NAME
NAME="John" echo "$NAME"
echo "Hello $NAME!" echo "${NAME}!"
Sh
Conditional execution Functions
git commit && git push get_name() {
git commit || echo "Commit failed" echo "John"
}
Conditionals echo "You are $(get_name)"
if [[ -z "$string" ]]; then See: Functions St
echo "String is empty"
elif [[ -n "$string" ]]; then
echo "String is not empty" Brace expansion
fi
echo {A,B}.js
See: Conditionals
{A,B}
{A,B}.js
{1..5}
See: Brace expansion
[Link] 1/9
8/31/2019 Bash scripting cheatsheet
# Parameter expansions
Basics Substitution Co
name="John" ${FOO%suffix}
echo ${name}
echo ${name/J/j} #=> "john" (substitution) ${FOO#prefix}
echo ${nam[Link]} #=> "Jo" (slicing)
echo ${name::2} #=> "Jo" (slicing) ${FOO%%suffix}
echo ${name::-1} #=> "Joh" (slicing)
echo ${name:(-1)} #=> ${FOO##prefix}
"n" (slicing from right)
echo ${name:(-2):1} #=> "h" (slicing from right)
echo ${food:-Cake} #=> $food or "Cake" ${FOO/from/to}
${FOO//from/to}
Su
length=2
echo ${nam[Link]length} #=> "Jo"
${FOO/%from/to}
${FOO/#from/to}
See: Parameter expansion
Length M
STR="/path/to/[Link]"
echo ${STR%.cpp} # /path/to/foo
echo ${STR%.cpp}.o # /path/to/foo.o ${#FOO}
echo ${STR##*.} # cpp (extension)
Default values
echo ${STR##*/} # [Link] (basepath)
echo ${STR#*/} # path/to/[Link] ${FOO:-val}
echo ${STR##*/} # [Link]
${FOO:=val}
echo ${STR/foo/bar} # /path/to/[Link]
${FOO:+val}
STR="Hello world"
${FOO:?message}
echo ${STR:6:5} # "world"
echo ${STR:-5:5} # "world"
The : is optional (eg, ${FOO=word} works)
SRC="/path/to/[Link]"
BASE=${SRC##*/} #=> "[Link]" (basepath)
DIR=${SRC%$BASE} #=> "/path/to/" (dirpath)
[Link] 2/9
8/31/2019 Bash scripting cheatsheet
# Loops
Basic for loop C-like for loop Ra
for i in /etc/rc.*; do for ((i = 0 ; i < 100 ; i++)); do
echo $i echo $i
done done
Reading lines Forever
< [Link] | while read line; do while true; do
echo $line ···
done done
# Functions
Defining functions Returning values Ra
myfunc() { myfunc() {
echo "hello $1" local myresult='some value'
} echo $myresult
}
# Same as above (alternate syntax)
function myfunc() { result="$(myfunc)"
echo "hello $1"
}
Arguments
myfunc "John"
$#
$*
$@
$1
See Special parameters.
[Link] 3/9
8/31/2019 Bash scripting cheatsheet
# Conditionals
Conditions File conditions Ex
[[ -e FILE ]]
Note that [[ is actually a command/program that returns either 0 (true) or 1 (false). Any program that obeys
the same logic (like all base utils, such as grep(1) or ping(1)) can be used as condition, see examples.
[[ -r FILE ]]
[[ -z STRING ]] [[ -h FILE ]] Empty string
[[ -n STRING ]] [[ -d FILE ]] Not empty string
[[ STRING == STRING ]] [[ -w FILE ]] Equal
[[ STRING != STRING ]] [[ -s FILE ]] Not Equal
[[ NUM -eq NUM ]] [[ -f FILE ]] Equal
[[ NUM -ne NUM ]] [[ -x FILE ]] Not equal
[[ NUM -lt NUM ]] [[ FILE1 -nt FILE2 ]] Less than
[[ NUM -le NUM ]] [[ FILE1 -ot FILE2 ]] Less than or equal
[[ NUM -gt NUM ]] [[ FILE1 -ef FILE2 ]] Greater than
[[ NUM -ge NUM ]] Greater than or equal
[[ STRING =~ STRING ]] Regexp
(( NUM < NUM )) Numeric conditions
[[ -o noclobber ]] If OPTIONNAME is enabled
[[ ! EXPR ]] Not
[[ X ]] && [[ Y ]] And
[[ X ]] || [[ Y ]] Or
[Link] 4/9
8/31/2019 Bash scripting cheatsheet
# Arrays
Defining arrays Working with arrays
Fruits=('Apple' 'Banana' 'Orange') echo ${Fruits[0]}
echo ${Fruits[@]}
echo ${#Fruits[@]}
Fruits[0]="Apple"
echo ${#Fruits}
Fruits[1]="Banana"
echo ${#Fruits[3]}
Fruits[2]="Orange"
echo ${Fruits[@]:3:2}
Operations Iteration
Fruits=("${Fruits[@]}" "Watermelon") # Push
for i in "${arrayName[@
Fruits+=('Watermelon') # Also Push
echo $i
Fruits=( ${Fruits[@]/Ap*/} ) # Remove by regex match
done
unset Fruits[2] # Remove one item
Fruits=("${Fruits[@]}") # Duplicate
Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate
lines=(`cat "logfile"`) # Read from file
# Dictionaries
Defining Working with dictionaries Ite
declare -A sounds echo ${sounds[dog]} # Dog's sound
echo ${sounds[@]} # All values
echo ${!sounds[@]} # All keys
sounds[dog]="bark"
echo ${#sounds[@]} # Number of elements
sounds[cow]="moo"
unset sounds[dog] # Delete dog
sounds[bird]="tweet"
sounds[wolf]="howl"
Declares sound as a Dictionary object (aka associative array).
[Link] 5/9
8/31/2019 Bash scripting cheatsheet
# Options
Options Glob options
set -o noclobber # Avoid overlay files (echo "hi" > foo) set -o nullglob # No
set -o errexit # Used to exit upon error, avoiding cascading errorsset -o failglob # No
set -o pipefail # Unveils hidden failures set -o nocaseglob # Cas
set -o nounset # Exposes unset variables set -o globdots # Wil
set -o globstar # All
Set GLOBIGNORE as a colon-s
# History
Commands Expansions
history !$ Show history
shopt -s histverify Don’t execute expanded
!* result immediately
!-n
Operations
!n
!! Execute last command again
!<command>
!!:s/<FROM>/<TO>/ Replace first occurrence of <FROM> to <TO> in most recent command
Slices
!!:gs/<FROM>/<TO>/ Replace all occurrences of <FROM> to <TO> in most recent command
!$:t most recent command Expa
Expand only basename from last parameter of!!:n
!$:h Expand only directory from last parameter of!^
most recent command
!$
!! and !$ can be replaced with any valid expansion.
!!:n-m
!!:n-$
[Link] 6/9
8/31/2019 Bash scripting cheatsheet
!! can be replaced with any v
# Miscellaneous
Numeric calculations Subshells
$((a + 200)) # Add 200 to $a (cd somedir; echo "I'm
pwd # still in first di
$((RANDOM%=200)) # Random number 0..200
Redirection
Inspecting commands
python [Link] > outpu
python [Link] >> outp
command -V cd
python [Link] 2> erro
#=> "cd is a function/alias/whatever"
python [Link] 2>&1
python [Link] 2>/dev/
python [Link] &>/dev/
Trap errors
python [Link] < [Link]
trap 'echo Error at about $LINENO' ERR
or
Case/switch
traperr() {
case "$1" in
echo "ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}"
start | up)
}
vagrant up
;;
set -o errtrace
trap traperr ERR
*)
echo "Usage: $0 {sta
;;
Source relative esac
source "${0%/*}/../share/[Link]"
printf
Directory of script printf "Hello %s, I'm %s
#=> "Hello Sven, I'm Olg
[Link] 7/9
8/31/2019 Bash scripting cheatsheet
DIR="${0%/*}" Getting options
Heredoc
while [[ "$1" =~ ^- &&
cat <<END -V | --version )
hello world echo $version
END exit
;;
-s | --string )
Reading input shift; string=$1
;;
-f | --flag )
echo -n "Proceed? [y/n]: " flag=1
read ans ;;
echo $ans esac; shift; done
if [[ "$1" == '--' ]]; t
read -n 1 ans # Just one character
Special variables
Go to previous directory
$?
pwd # /home/user/foo $!
cd bar/
pwd # /home/user/foo/bar $$
cd -
pwd # /home/user/foo
See Special parameters.
# Also see
Bash-hackers wiki ([Link])
Shell vars ([Link])
Learn bash in y minutes ([Link])
Bash Guide ([Link])
ShellCheck ([Link])
[Link] 8/9
8/31/2019 Bash scripting cheatsheet
15 Comments for this cheatsheet. Write yours!
Search 381+ cheatsheets
Over 381 curated cheatsheets, by developers for developers.
Devhints home
Other CLI cheatsheets Top cheatsheets
Cron Homebrew Elixir ES2015+
cheatsheet cheatsheet cheatsheet cheatsheet
httpie adb (Android [Link] Vimdiff
cheatsheet Debug Bridge) cheatsheet cheatsheet
cheatsheet
Vim Vim scripting
composer Fish shell cheatsheet cheatsheet
cheatsheet cheatsheet
[Link] 9/9