Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
26 views

Bash Scripting Cheatsheet

Bash scripting cheatsheet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Bash Scripting Cheatsheet

Bash scripting cheatsheet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

6/15/23, 10:53 PM Bash scripting cheatsheet

DEVHINTS.IO Edit

Bash scripting cheatsheet


Introduction Example Variables

This is a quick reference to getting started with Bash scripting.


#!/usr/bin/env bash name="John"
echo $name # see below
name="John" echo "$name"
Learn bash in y minutes echo "Hello $name!" echo "${name}!"
(learnxinyminutes.com)

Generally quote your variables unless they contain wildcards to expand or co


Bash Guide String quotes
(mywiki.wooledge.org)
wildcard="*.txt"
name="John"
Bash Hackers Wiki option="iv"
echo "Hi $name" #=> Hi John
(wiki.bash-hackers.org) cp -$options $wildcard /tmp
echo 'Hi $name' #=> Hi $name

Conditional execution Shell execution Functions

git commit && git push echo "I'm in $(pwd)"


get_name() {
git commit || echo "Commit failed" echo "I'm in `pwd`" # obsolescent
echo "John"
# Same
}

Conditionals See Command substitution echo "You are $(get_name)"

if [[ -z "$string" ]]; then See: Functions


echo "String is empty" Strict mode
elif [[ -n "$string" ]]; then
echo "String is not empty"
set -euo pipefail Brace expansion
fi
IFS=$'\n\t'
echo {A,B}.js
See: Conditionals
See: Unofficial bash strict mode
{A,B}

{A,B}.js

{1..5}

See: Brace expansion

https://devhints.io/bash 1/9
6/15/23, 10:53 PM Bash scripting cheatsheet

# Parameter expansions
Basics Substitution Comments

name="John" ${foo%suffix} # Single line comment


echo "${name}"
echo "${name/J/j}" #=> "john" (substitution) ${foo#prefix}
: '
echo "${name:0:2}" #=> "Jo" (slicing)
${foo%%suffix} This is a
echo "${name::2}" #=> "Jo" (slicing)
multi line
echo "${name::-1}" #=> "Joh" (slicing)
comment
echo "${name:(-1)}" #=> "n" (slicing from right) ${foo/%suffix}
'
echo "${name:(-2):1}" #=> "h" (slicing from right)
${foo##prefix}
echo "${food:-Cake}" #=> $food or "Cake"

${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

echo "${str##*.}" # cpp (extension) Default values


str="HELLO WORLD!"
echo "${str##*/}" # foo.cpp (basepath)
echo "${str,}" #=> "hELLO WORLD!" (lowercase 1st letter)
echo "${str,,}" #=> "hello world!" (all lowercase)${foo:-val}
echo "${str#*/}" # path/to/foo.cpp
echo "${str##*/}" # foo.cpp ${foo:=val}
str="hello world!"
echo "${str^}" #=> "Hello world!" (uppercase 1st letter)
echo "${str/foo/bar}" # /path/to/bar.cpp
echo "${str^^}" #=> "HELLO WORLD!" (all uppercase)${foo:+val}

str="Hello world" ${foo:?message}


echo "${str:6:5}" # "world"
echo "${str: -5:5}" # "world" Omitting the : removes the (non)nullity checks, e.g. ${foo-val} expands to

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

for i in /etc/rc.*; do for ((i = 0 ; i < 100 ; i++)); do for i in {1..5}; do


echo "$i" echo "$i" echo "Welcome $i"
done done done

With step size


Reading lines Forever
for i in {5..50..5}; do
while read -r line; do while true; do echo "Welcome $i"
echo "$line" ··· done
done <file.txt done

# Functions
Defining functions Returning values Raising errors

myfunc() { myfunc() { myfunc() {


echo "hello $1" local myresult='some value' return 1
} echo "$myresult" }
}

# Same as above (alternate syntax) if myfunc; then


function myfunc() { result=$(myfunc) echo "success"
echo "hello $1" else
} echo "failure"
Arguments fi

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

See Special parameters.

# Conditionals
https://devhints.io/bash 3/9
6/15/23, 10:53 PM Bash scripting cheatsheet

Conditions File conditions Example

[[ -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

[[ STRING != STRING ]] [[ -s FILE ]] # Combinations Not Equal


if [[ X && Y ]]; then
[[ NUM -eq NUM ]] [[ -f FILE ]] ... Equal
fi
[[ NUM -ne NUM ]] [[ -x FILE ]] Not equal

[[ NUM -lt NUM ]] # Equal Less than


[[ FILE1 -nt FILE2 ]]
if [[ "$A" == "$B" ]]
[[ NUM -le NUM ]] [[ FILE1 -ot FILE2 ]] Less than or equal
# Regex
[[ NUM -gt NUM ]] [[ FILE1 -ef FILE2 ]] Greater than
if [[ "A" =~ . ]]

[[ NUM -ge NUM ]] Greater than or equal


if (( $a < $b )); then
[[ STRING =~ STRING ]] echo "$a is smaller than $b" Regexp
fi
(( NUM < NUM )) Numeric conditions

More conditions if [[ -e "file.txt" ]]; then


echo "file exists"
[[ -o noclobber ]] fi If OPTIONNAME is enabled

[[ ! EXPR ]] Not

[[ X && Y ]] And

[[ X || Y ]] Or

# Arrays
Defining arrays Working with arrays

Fruits=('Apple' 'Banana' 'Orange') echo "${Fruits[0]}" # Element #0


echo "${Fruits[-1]}" # Last element

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

Fruits=("${Fruits[@]}" "Watermelon") # Push Iteration


Fruits+=('Watermelon') # Also Push
Fruits=( "${Fruits[@]/Ap*/}" ) # Remove by regex match for i in "${arrayName[@]}"; do
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 Iteration

Iterate over values


declare -A sounds echo "${sounds[dog]}" # Dog's sound
echo "${sounds[@]}" # All values
for val in "${sounds[@]}"; do
echo "${!sounds[@]}" # All keys
sounds[dog]="bark" echo "$val"
echo "${#sounds[@]}" # Number of elements
sounds[cow]="moo" done
unset sounds[dog] # Delete dog
sounds[bird]="tweet"
sounds[wolf]="howl" Iterate over keys

for key in "${!sounds[@]}"; do


Declares sound as a Dictionary object (aka associative array). echo "$key"
done

# 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

Set GLOBIGNORE as a colon-separated list of patterns to be removed from glob matches.

# 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 !!: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

$(($RANDOM%200)) # Random number 0..199

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

Inspecting commands python hello.py 2> error.log # stderr to (file)


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), equivalent to &>
#=> "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 stderr

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

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 {start|stop|ssh}"
;;
Source relative esac

source "${0%/*}/../share/foo.sh" printf

printf "Hello %s, I'm %s" Sven Olga


Transform strings #=> "Hello Sven, I'm Olga

-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"

-t printf '%s\n' '#!/bin/bash' 'echo hello' >file Truncates


# format string is applied to each group of arguments
[:upper:] printf '%i+%i=%i\n' 1 2 3 4 5 9 All upper case letters

[:lower:] All lower case letters


Directory of script
[:digit:] All digits

dir=${0%/*}
[:space:] All whitespace

[:alpha:] All letters


Getting options
[:alnum:] All letters and digits

Example while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in


-V | --version )

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"
$!

The -r option disables a peculiar legacy behavior with backslashes. $$

read -n 1 ans # Just one character $0

$_

Go to previous directory
${PIPESTATUS[n]}

pwd # /home/user/foo See Special parameters.


cd bar/
pwd # /home/user/foo/bar
cd - Check for command’s result
pwd # /home/user/foo

if ping -c 1 google.com; then


Grep check echo "It appears you have a working internet connection"
fi

if grep -q 'foo' ~/.bash_history; then


echo "You appear to have typed 'foo' in the past"
fi

# Also see
Bash-hackers wiki (bash-hackers.org)

Shell vars (bash-hackers.org)

Learn bash in y minutes (learnxinyminutes.com)

https://devhints.io/bash 8/9
6/15/23, 10:53 PM Bash scripting cheatsheet

Bash Guide (mywiki.wooledge.org)

ShellCheck (shellcheck.net)

41 Comments for this cheatsheet. Write yours!

Search 358+ cheatsheets

Over 358 curated cheatsheets, by developers for developers.

Devhints home

Other CLI cheatsheets Top cheatsheets

Cron Homebrew Elixir ES2015+


cheatsheet cheatsheet cheatsheet cheatsheet

httpie adb (Android Debug Bridge) React.js Vimdiff


cheatsheet cheatsheet cheatsheet cheatsheet

composer Fish shell Vim Vim scripting


cheatsheet cheatsheet cheatsheet cheatsheet

https://devhints.io/bash 9/9

You might also like