Bash Scripting Cheatsheet
Bash Scripting Cheatsheet
DEVHINTS.IO Edit
{A,B}.js
{1..5}
https://devhints.io/bash 1/9
6/15/23, 10:53 PM Bash scripting cheatsheet
# Parameter expansions
Basics Substitution Comments
${foo/#prefix} Substrings
length=2
echo "${name:0:length}" #=> "Jo" ${foo/from/to} ${foo:0:3}
${foo//from/to} ${foo:(-3):3}
See: Parameter expansion
${foo/%from/to}
str="/path/to/foo.cpp" Length
echo "${str%.cpp}" # /path/to/foo ${foo/#from/to}
echo "${str%.cpp}.o" # /path/to/foo.o ${#foo}
echo "${str%/*}" # /path/to Manipulation
src="/path/to/foo.cpp"
base=${src##*/} #=> "foo.cpp" (basepath)
dir=${src%$base} #=> "/path/to/" (dirpath)
# Loops
Basic for loop C-like for loop Ranges
https://devhints.io/bash 2/9
6/15/23, 10:53 PM Bash scripting cheatsheet
# Functions
Defining functions Returning values Raising errors
myfunc "John"
$#
$* All
$@ All po
$1
$_ L
Note: $@ and $* must be quoted in order to perform as described. Otherwise, they do exactly the same thing (arguments as separate strings
# Conditionals
https://devhints.io/bash 3/9
6/15/23, 10:53 PM Bash scripting cheatsheet
[[ -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
String
used as condition, see examples. if [[ -z "$string" ]]; then
[[ -r FILE ]] echo "String is empty"
elif [[ -n "$string" ]]; then
[[ -z STRING ]] [[ -h FILE ]] Empty string
echo "String is not empty"
else
[[ -n STRING ]] [[ -d FILE ]] Not empty string
echo "This never happens"
fi
[[ STRING == STRING ]] [[ -w FILE ]] Equal
[[ ! EXPR ]] Not
[[ X && Y ]] And
[[ X || Y ]] Or
# Arrays
Defining arrays Working with arrays
https://devhints.io/bash 4/9
6/15/23, 10:53 PM Bash scripting cheatsheet
echo "${Fruits[@]}" # All elements, space-separated
Fruits[0]="Apple" echo "${#Fruits[@]}" # Number of elements
Fruits[1]="Banana" echo "${#Fruits}" # String length of the 1st element
Fruits[2]="Orange" echo "${#Fruits[3]}" # String length of the Nth element
echo "${Fruits[@]:3:2}" # Range (from position 3, length 2)
Operations echo "${!Fruits[@]}" # Keys of all elements, space-separated
# Dictionaries
Defining Working with dictionaries Iteration
# Options
Options Glob options
set -o noclobber # Avoid overlay files (echo "hi" > foo) shopt -s nullglob # Non-matching globs are removed ('*.foo' => '')
set -o errexit # Used to exit upon error, avoiding cascading errors shopt -s failglob # Non-matching globs throw errors
set -o pipefail # Unveils hidden failures shopt -s nocaseglob # Case insensitive globs
set -o nounset # Exposes unset variables shopt -s dotglob # Wildcards match dotfiles ("*.sh" => ".foo.sh")
shopt -s globstar # Allow ** for recursive matches ('lib/**/*.rb' => 'lib/a/b/c.rb')
https://devhints.io/bash 5/9
6/15/23, 10:53 PM Bash scripting cheatsheet
# History
Commands Expansions
!-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 !!:n Expand only basename from last parameter of most recent command Expand only nt
!$:h !^ Expand only directory from last parameter of most recent command
!$
!! and !$ can be replaced with any valid expansion.
!!:n-m
!!:n-$
!! can be replaced with any valid expansion i.e. !cat, !-2, !42, etc.
# Miscellaneous
Numeric calculations Subshells
$((a + 200)) # Add 200 to $a (cd somedir; echo "I'm now in $PWD")
pwd # still in first directory
Redirection
declare -i count # Declare as type integer
count+=1 # Increment
python hello.py > output.txt # stdout to (file)
python hello.py >> output.txt # stdout to (file), append
https://devhints.io/bash 6/9
6/15/23, 10:53 PM Bash scripting cheatsheet
Trap errors
python hello.py < foo.txt # feed foo.txt to stdin for python
diff <(ls -r) <(ls) # Compare two stdout without files
trap 'echo Error at about $LINENO' ERR
or Case/switch
-c printf "1 + 1 = %d" 2 Operations apply to characters not in the given set
#=> "1 + 1 = 2"
-d Delete characters
printf "This is how you print a float: %f" 2
-s #=> "This is how you print Replaces
a float: repeated characters with single occurrence
2.000000"
dir=${0%/*}
[:space:] All whitespace
https://devhints.io/bash 7/9
6/15/23, 10:53 PM Bash scripting cheatsheet
echo "$version"
echo "Welcome To Devhints" | tr '[:lower:]' '[:upper:]' exit
WELCOME TO DEVHINTS ;;
Heredoc -s | --string )
shift; string=$1
;;
cat <<END
-f | --flag )
hello world
flag=1
END
;;
esac; shift; done
if [[ "$1" == '--' ]]; then shift; fi
Reading input
Special variables
echo -n "Proceed? [y/n]: "
read -r ans $?
echo "$ans"
$!
$_
Go to previous directory
${PIPESTATUS[n]}
# Also see
Bash-hackers wiki (bash-hackers.org)
https://devhints.io/bash 8/9
6/15/23, 10:53 PM Bash scripting cheatsheet
ShellCheck (shellcheck.net)
Devhints home
https://devhints.io/bash 9/9