DEVHINTS.
IO
Edit
Bash scripting cheatsheet
Your new development career
awaits. Check out the latest listings.
ads via Carbon
Introduction Example
This is a quick reference to getting started with Bash scripting.
#!/usr/bin/env bash
NAME="John"
Learn bash in y minutes echo "Hello $NAME!"
(learnxinyminutes.com)
Bash Guide
String quotes
(mywiki.wooledge.org)
NAME="John"
echo "Hi $NAME" #=> Hi John
Conditional execution echo 'Hi $NAME' #=> Hi $NAME
git commit && git push
Functions
git commit || echo "Commit failed"
get_name() {
Strict mode echo "John"
set -euo pipefail
echo "You are $(get_name)"
IFS=$'\n\t'
See: Functions
See: Unofficial bash strict mode
Brace expansion
echo {A,B}.js
{A,B}
{A,B}.js
{1..5}
See: Brace expansion
# Parameter expansions
Basics Substitution
name="John"
${FOO%suffix}
echo ${name}
echo ${name/J/j} #=> "john" (substitution)
${FOO#prefix}
echo ${name:0:2} #=> "Jo" (slicing)
echo ${name::2} #=> "Jo" (slicing)
${FOO%%suffix}
echo ${name::-1} #=> "Joh" (slicing)
echo ${name:(-1)} #=> "n" (slicing from right)
${FOO##prefix}
echo ${name:(-2):1} #=> "h" (slicing from right)
echo ${food:-Cake} #=> $food or "Cake"
${FOO/from/to}
${FOO//from/to}
length=2
echo ${name:0:length} #=> "Jo"
${FOO/%from/to}
${FOO/#from/to}
See: Parameter expansion
STR="/path/to/foo.cpp"
Length
echo ${STR%.cpp} # /path/to/foo
echo ${STR%.cpp}.o # /path/to/foo.o
${#FOO}
echo ${STR%/*} # /path/to
echo ${STR##*.} # cpp (extension)
Default values
echo ${STR##*/} # foo.cpp (basepath)
echo ${STR#*/} # path/to/foo.cpp
${FOO:-val}
echo ${STR##*/} # foo.cpp
${FOO:=val}
echo ${STR/foo/bar} # /path/to/bar.cpp
${FOO:+val}
${FOO:?message}
STR="Hello world"
echo ${STR:6:5} # "world"
echo ${STR: -5:5} # "world"
Omitting the : removes the (non)nullity checks, e
SRC="/path/to/foo.cpp"
BASE=${SRC##*/} #=> "foo.cpp" (basepath)
DIR=${SRC%$BASE} #=> "/path/to/" (dirpath)
# Loops
Basic for loop C-like for loop
for i in /etc/rc.*; do
for ((i = 0 ; i < 100 ; i++)); do
echo $i
echo $i
done
done
Reading lines Forever
cat file.txt | while read line; do
while true; do
echo $line
···
done
done
# Functions
Defining functions Returning values
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
$_
Note: $@ and $* must be quoted in order to perf
(arguments as separate strings).
See Special parameters.
# Conditionals
Conditions File conditions
[[ -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
More conditions
[[ -o noclobber ]] If OPTIONNAME is enabled
[[ ! EXPR ]] Not
[[ X && Y ]] And
[[ X || Y ]] Or
# Arrays
Defining arrays Working with
Fruits=('Apple' 'Banana' 'Orange')
echo ${Fruit
echo ${Fruit
echo ${Fruit
Fruits[0]="Apple"
echo ${#Frui
Fruits[1]="Banana"
echo ${#Frui
Fruits[2]="Orange"
echo ${#Frui
echo ${Fruit
echo ${!Frui
Operations
Fruits=("${Fruits[@]}" "Watermelon") # Push
Iteration
Fruits+=('Watermelon') # Also Push
Fruits=( ${Fruits[@]/Ap*/} ) # Remove by regex match
for i in "${
unset Fruits[2] # Remove one item
echo $i
Fruits=("${Fruits[@]}") # Duplicate
done
Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate
lines=(`cat "logfile"`) # Read from file
# Dictionaries
Defining Working with dictionaries
declare -A sounds
echo ${sounds[dog]} # Dog's sound
echo ${sounds[@]} # All values
echo ${!sounds[@]} # All keys
sounds[dog]="bark"
echo ${#sounds[@]} # Number of element
sounds[cow]="moo"
unset sounds[dog] # Delete dog
sounds[bird]="tweet"
sounds[wolf]="howl"
Declares sound as a Dictionary object (aka associative array).
# Options
Options Glob options
set -o noclobber # Avoid overlay files (echo "hi" > foo)
shopt -s nul
set -o errexit # Used to exit upon error, avoiding cascading errors
shopt -s fai
set -o pipefail # Unveils hidden failures
shopt -s noc
set -o nounset # Exposes unset variables
shopt -s dot
shopt -s glo
Set GLOBIGNOR
# 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
!!:gs/<FROM>/<TO>/
Slices
Replace all occurrences of <FROM> to <TO> in most recent command
!$:t Expand only basename from last parameter of most recent command
!!:n
!$:h Expand only directory from last parameter of most recent command
!^
!$
!! and !$ can be replaced with any valid expansion.
!!:n-m
!!:n-$
!! can be repla
# Miscellaneous
Numeric calculations Subshells
$((a + 200)) # Add 200 to $a
(cd somedir;
pwd # still
$(($RANDOM%200)) # Random number 0..199
Redirection
Inspecting commands
python hello
python hello
command -V cd
python hello
#=> "cd is a function/alias/whatever"
python hello
python hello
python hello
Trap errors
python hello
diff <(ls -r
trap 'echo Error at about $LINENO' ERR
Case/switch
or
case "$1" in
traperr() {
start | up
echo "ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}"
vagrant
}
;;
set -o errtrace
*)
trap traperr ERR
echo "Us
;;
Source relative esac
source "${0%/*}/../share/foo.sh"
printf
Transform strings printf "Hell
#=> "Hello Sv
-c Operations apply to characters not in the given set
printf "1 +
#=> "1 + 1 =
-d Delete characters
printf "This
-s Replaces repeated characters with single occurrence
#=> "This is
-t Truncates
[:upper:] All upperDirectory
case letters of s
[:lower:] All lower case letters
DIR="${0%/*}
[:digit:] All digits
[:space:] AllGetting optio
whitespace
[:alpha:] All letters
while [[ "$1
-V | --ver
[:alnum:] All letters and digits
echo $ve
Example exit
;;
echo "Welcome To Devhints" | tr [:lower:] [:upper:]
-s | --str
WELCOME TO DEVHINTS
shift; s
;;
-f | --fla
Heredoc flag=1
;;
cat <<END
esac; shift;
hello world
if [[ "$1" ==
END
Reading inpu
Special variables
echo -n "Pro
read ans
$? Exit status of last task
echo $ans
$! PID of last background task
read -n 1 an
$$ PID of shell
Filename of the shell script
$0
Go to previou
$_ Last argument of the previous command
pwd # /home/
cd bar/
See Special parameters.
pwd # /home/
cd -
pwd # /home/
Check for command’s result
if ping -c 1 google.com; then
Grep check
echo "It appears you have a working internet connection"
fi
if grep -q '
echo "You
fi
# Also see
Bash-hackers wiki (bash-hackers.org)
Shell vars (bash-hackers.org)
Learn bash in y minutes (learnxinyminutes.com)
Bash Guide (mywiki.wooledge.org)
ShellCheck (shellcheck.net)
32 Comments
for this cheatsheet.
Write yours!
Search 356+ cheatsheets
Over 356 curated cheatsheets, by developers for developers.
Devhints home
Other CLI cheatsheets Top cheatsheets
Cron Homebrew Elixir ES2015+
cheatsheet
cheatsheet
cheatsheet
cheatsheet
httpie adb (Android React.js Vimdiff
cheatsheet
Debug Bridge) cheatsheet
cheatsheet
cheatsheet
Vim Vim scripting
composer Fish shell cheatsheet
cheatsheet
cheatsheet
cheatsheet