Bash scripting cheatsheet
Esempio
#!/usr/bin/env bash
NAME="John"
echo "Hello $NAME!"
Variabili
NAME="John"
echo $NAME
echo "$NAME"
echo "${NAME}!"
Quotes delle stringhe
NAME="John"
echo "Hi $NAME" #=> Hi John
echo 'Hi $NAME' #=> Hi $NAME
Esecuzione di comandi
echo "I'm in $(pwd)"
echo "I'm in `pwd`"
# Same
Esecuzione condizionale
git commit && git push
git commit || echo "Commit failed"
Funzioni
get_name() {
echo "John"
}
echo "You are $(get_name)"
If.. Then.. Else...
if [[ -z "$string" ]]; then
echo "String is empty"
elif [[ -n "$string" ]]; then
echo "String is not empty"
fi
Strict mode
set -euo pipefail
IFS=$'\n\t'
Espansione di stringhe
echo {A,B}.js
|
Same as |
|
Same as |
|
Same as |
Manipolazione di stringhe
Basics
name="John"
echo ${name}
echo ${name/J/j}
#=> "john" (substitution)echo ${name:0:2}
#=> "Jo" (slicing)echo ${name::2}
#=> "Jo" (slicing)echo ${name::-1}
#=> "Joh" (slicing)echo ${name:(-1)}
#=> "n" (slicing from right)echo ${name:(-2):1}
#=> "h" (slicing from right)echo ${food:-Cake}
#=> $food or "Cake"length=2
echo ${name:0:length}
#=> "Jo"
STR="/path/to/foo.cpp"
echo ${STR%.cpp}
# /path/to/fooecho ${STR%.cpp}.o
# /path/to/foo.oecho ${STR##*.}
# cpp (extension)echo ${STR##*/}
# foo.cpp (basepath)echo ${STR#*/}
# path/to/foo.cppecho ${STR##*/}
# foo.cppecho
${STR/foo/bar}
# /path/to/bar.cppSTR="Hello world"
echo ${STR:6:5}
# "world"echo ${STR:-5:5}
# "world"SRC="/path/to/foo.cpp"
BASE=${SRC##*/}
#=> "foo.cpp" (basepath)DIR=${SRC%$BASE}
#=> "/path/to/" (dirpath)
Sostituzione
|
Remove suffix |
|
Remove prefix |
|
Remove long suffix |
|
Remove long prefix |
|
Replace first match |
|
Replace all |
|
Replace suffix |
|
Replace prefix |
Sottostringhe
|
Substring (position, length) |
|
Substring from the right |
Lunghezza
|
Length of |
Valori di default
|
|
|
Set |
|
|
|
Show error message and exit if |
The :
is optional (eg, ${FOO=word}
works)
Cicli
For
for i in /etc/rc.*; do
echo $i
done
For (C-like)
for ((i = 0 ; i < 100 ; i++)); do
echo $i
done
For (Intervallo)
for i in {1..5}; do
echo "Welcome $i"
done
For (Intervallo e passo)
for i in {5..50..5}; do
echo "Welcome $i"
done
Lettura di righe da file
< file.txt | while read line; do
echo
$linedone
Ciclo infinito
while true; do
···
done
Funzioni
Definizione di funzioni
myfunc() {
echo "hello $1"
}
# Same as above (alternate syntax)
function myfunc() {
echo "hello $1"
}
myfunc "John"
Valori di ritorno
myfunc() {
local myresult='some value'
echo $myresult
}
result="$(myfunc)"
Gestione errori
myfunc() {
return 1
}
if myfunc; then
echo "success"
else
echo "failure"
fi
Argomenti delle funzioni
|
Number of arguments |
|
All arguments |
|
All arguments, starting from first |
|
First argument |
Espressioni condizionali
Conditioni
NB [[
è un comando a tutti gli effetti che restituisce 0
(true) o 1
(false). Qualunque programma che utilizza la stessa logica (come tutti quelli base come grep(1)
o ping(1)
) possono essere usati come condizioni.
|
Stringa vuota |
|
Stringa non vuota |
|
Uguaglianza fra stringhe |
|
Disuguaglianzafra stringhe |
|
Uguaglianza fra numeri |
|
guaglianza fra numeri |
|
Minore |
|
Minore o uguale |
|
Maggiore |
|
Maggiore o uguale |
|
Espressione regolare |
|
Condizioni numeriche |
[[ -o noclobber ]] |
If OPTIONNAME is enabled |
|
Not |
|
And |
|
Or |
Condizioni sui file
|
Exists |
|
Readable |
|
Symlink |
|
Directory |
|
Writable |
|
Size is > 0 bytes |
|
File |
|
Executable |
|
1 is more recent than 2 |
|
2 is more recent than 1 |
|
Same files |
Example
if ping -c 1 google.com; then
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
# String
if [[ -z "$string" ]]; then
echo "String is empty"
elif [[ -n "$string" ]]; then
echo "String is not empty"
fi
# Combinations
if [[ X ]] && [[ Y ]]; then
...
fi
# Equal
if [[ "$A" == "$B" ]]
# Regex
if [[ "A" =~ "." ]]
if (( $a < $b )); then
echo "$a is smaller than $b"
fi
if [[ -e "file.txt" ]]; then
echo "file exists"
fi
Arrays
Defining arrays
Fruits=('Apple' 'Banana' 'Orange')
Fruits[0]="Apple"
Fruits[1]="Banana"
Fruits[2]="Orange"
Working with arrays
echo ${Fruits[0]} # Element #0
echo ${Fruits[@]} # All elements, space-separated
echo ${#Fruits[@]} # Number of elements
echo ${#Fruits} # String length of the 1st element
echo ${#Fruits[3]} # String length of the Nth element
echo ${Fruits[@]:3:2} # Range (from position 3, length 2)
Operations
Fruits=("${Fruits[@]}" "Watermelon") # Push
Fruits+=('Watermelon') # Also Push
Fruits=( ${Fruits[@]/Ap*/} ) # Remove by regex match
unset Fruits[2] # Remove one item
Fruits=("${Fruits[@]}") # Duplicate
Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate
lines=(`cat "logfile"`) # Read from file
Iteration
for i in "${arrayName[@]}"; do
echo $i
done
Dictionaries
Defining
declare -A sounds
sounds[dog]="bark"
sounds[cow]="moo"
sounds[bird]="tweet"
sounds[wolf]="howl"
Declares sound
as a Dictionary object (aka associative array).
Working with dictionaries
echo ${sounds[dog]} # Dog's sound
echo ${sounds[@]} # All values
echo ${!sounds[@]} # All keys
echo ${#sounds[@]} # Number of elements
unset sounds[dog] # Delete dog
Iteration
Iterate over values
for val in "${sounds[@]}"; do
echo $val
done
Iterate over keys
for key in "${!sounds[@]}"; do
echo $key
done
Options
Options
set -o noclobber # Avoid overlay files (echo "hi" > foo)
set -o errexit # Used to exit upon error, avoiding cascading errors
set -o pipefail # Unveils hidden failures
set -o nounset # Exposes unset variables
Glob options
set -o nullglob # Non-matching globs are removed ('*.foo' => '')
set -o failglob # Non-matching globs throw errors
set -o nocaseglob # Case insensitive globs
set -o globdots # Wildcards match dotfiles ("*.sh" => ".foo.sh")
set -o globstar # Allow ** for recursive matches ('lib/**/*.rb' => 'lib/a/b/c.rb')
Set GLOBIGNORE
as a colon-separated list of patterns to be removed from glob matches.
History
Commands
|
Show history |
|
Don’t execute expanded result immediately |
Expansions
|
Expand last parameter of most recent command |
|
Expand all parameters of most recent command |
|
Expand |
|
Expand |
|
Expand most recent invocation of command |
Operations
|
Execute last command again |
|
Replace first occurrence of |
|
Replace all occurrences of |
|
Expand only basename from last parameter of most recent command |
|
Expand only directory from last parameter of most recent command |
!!
and !$
can be replaced with any valid expansion.
Slices
|
Expand only |
|
Expand first argument from most recent command |
|
Expand last token from most recent command |
|
Expand range of tokens from most recent command |
|
Expand |
!!
can be replaced with any valid expansion i.e. !cat
, !-2
, !42
, etc.
Miscellaneous
Numeric calculations
$((a + 200)) # Add 200 to $a
$((RANDOM%=200)) # Random number 0..200
Subshells
(cd somedir; echo "I'm now in $PWD")
pwd # still in first directory
Redirection
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)
python hello.py 2>&1 # stderr to stdout
python hello.py 2>/dev/null # stderr to (null)
python hello.py &>/dev/null # stdout and stderr to (null)
python hello.py < foo.txt # feed foo.txt to stdin for python
Inspecting commands
command -V cd
#=> "cd is a function/alias/whatever"
Trap errors
trap 'echo Error at about $LINENO' ERR
or
traperr() {
echo "ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}"
}
set -o errtrace
trap traperr ERR
Case/switch
case "$1" in
start | up)
vagrant up
;;
*)
echo "Usage: $0 {start|stop|ssh}"
;;
esac
Source relative
source "${0%/*}/../share/foo.sh"
printf
printf "Hello %s, I'm %s" Sven Olga
#=> "Hello Sven, I'm Olga
Directory of script
DIR="${0%/*}"
Getting options
while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
-V | --version )
echo $version
exit
;;
-s | --string )
shift; string=$1
;;
-f | --flag )
flag=1
;;
esac; shift; done
if [[ "$1" == '--' ]]; then shift; fi
Heredoc
cat <<END
hello world
END
Reading input
echo -n "Proceed? [y/n]: "
read ans
echo $ans
read -n 1 ans # Just one character