Bash Scripting Cheatsheet
Bash Scripting Cheatsheet
IO Edit
echo {A,B}.js
See: Conditionals
See: Unofficial bash strict mode
{A,B} Same as A B
{1..5} Same as 1 2 3 4 5
# Parameter expansions
Basics Substitution Comments
# Functions
Defining functions Returning values Raising errors
$1 First argument
# Conditionals
Conditions File conditions Example
[[ -e FILE ]] Exists
Note that [[ is actually a command/program that returns # String
if [[ -z "$string" ]]; then
either 0 (true) or 1 (false). Any program that obeys the
[[ -r FILE ]] Readable echo "String is empty"
same logic (like all base utils, such as grep(1) or
elif [[ -n "$string" ]]; then
ping(1)) can be used as condition, see examples. [[ -h FILE ]] Symlink echo "String is not empty"
else
[[ -z STRING ]] Empty string [[ -d FILE ]] Directory echo "This never happens"
fi
[[ -n STRING ]] Not empty string [[ -w FILE ]] Writable
# Equal
[[ NUM -ne NUM ]] Not equal [[ FILE1 -nt FILE2 ]] 1 is more recent than 2
if [[ "$A" == "$B" ]]
[[ NUM -lt NUM ]] Less than [[ FILE1 -ot FILE2 ]] 2 is more recent than 1
# Regex
[[ NUM -le NUM ]] Less than or equal [[ FILE1 -ef FILE2 ]] Same files if [[ "A" =~ . ]]
[[ ! EXPR ]] Not
[[ X && Y ]] And
[[ X || Y ]] Or
# Arrays
Defining arrays Working with arrays
# 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
# History
Commands Expansions
shopt -s histverify Don’t execute expanded result immediately !* Expand all parameters of most recent command
!! 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
python hello.py 2> error.log # stderr to (file)
Inspecting commands python hello.py 2>&1 # stderr to stdout
python hello.py 2>/dev/null # stderr to (null)
command -V cd python hello.py >output.txt 2>&1 # stdout and stderr to (file), equiv
#=> "cd is a function/alias/whatever" python hello.py &>/dev/null # stdout and stderr to (null)
echo "$0: warning: too many users" >&2 # print diagnostic message to stder
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
source "${0%/*}/../share/foo.sh"
printf
-c Operations apply to characters not in the given set printf "1 + 1 = %d" 2
#=> "1 + 1 = 2"
-d Delete characters
printf "This is how you print a float: %f" 2
-s Replaces repeated characters with single occurrence #=> "This is how you print a float: 2.000000"
Directory of script
[:digit:] All digits
Example
while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
-V | --version )
echo "Welcome To Devhints" | tr '[:lower:]' '[:upper:]'
echo "$version"
WELCOME TO DEVHINTS
exit
;;
-s | --string )
Heredoc shift; string=$1
;;
-f | --flag )
cat <<END flag=1
hello world ;;
END esac; shift; done
if [[ "$1" == '--' ]]; then shift; fi
Reading input
Special variables
echo -n "Proceed? [y/n]: "
read -r ans $? Exit status of last task
echo "$ans"
$! PID of last background task
$$ PID of shell
$0 Filename of the shell script
The -r option disables a peculiar legacy behavior with backslashes.
Grep check echo "It appears you have a working internet connection"
fi
# Also see
Bash-hackers wiki (bash-hackers.org)
ShellCheck (shellcheck.net)
Over 358 curated cheatsheets, by httpie adb (Android Debug React.js Vimdiff
developers for developers. cheatsheet Bridge) cheatsheet cheatsheet
cheatsheet
Devhints home
Vim Vim scripting
composer Fish shell cheatsheet cheatsheet
cheatsheet cheatsheet