Cheatography
https://cheatography.com
Bash scripting Bash scripting
This is a draft cheat sheet. It is a work in progress and is not finished yet.
Globs
* |
Any number of characters inc. none |
*.txt |
test1.txt |
? |
Matches single character |
?.txt |
a.txt, not ab.txt |
[abc] |
Matches any one of enclosed characters |
[ab].txt |
a.txt, b.txt, not c.txt |
[a-c] |
Matches any character in the range |
[a-c].txt |
a.txt, b.txt, c.txt, not d.txt |
?(pattern-list) |
Extended: matches zero or one occurrence of the given patterns |
?(a|b).txt |
a.txt, b.txt, .txt |
*(pattern-list) |
Extended: matches zero or more occurrences of the given patterns |
*(a|b|c).txt |
a.txt, aa.txt, abac.txt, .txt |
+(pattern-list) |
Extended: matches one or more occurrences of the given patterns |
+(a|b|c).txt |
a.txt, ab.txt, ba.txt, aaabbbccc.txt, etc |
@(pattern-list) |
Extended: matches one of the given patterns |
@(a|b|c).txt |
a.txt, b.txt, or c.txt |
!(pattern-list) |
Extended: matches anything except one of the given patterns |
!(a|b|c).txt |
any .txt files except a.txt, b.txt, c.txt |
shopt -s extglob turns on extended globs.
shopt -s nullglob return no output if no matches, otherwise returns the glob pattern.
shopt -s nocaseglob makes globing case-insensitive.
shopt -s dotglob includes filenames starting with a dot (hidden files) in glob patterns.
|
For loop
Basic |
C-style syntax |
Over command output |
Over array elements |
for i in 1 2 3 4 5 do echo "Number $i" done
|
for ((i = 1; i <= 5; i++)) do echo "Number $i" done
|
for user in $(cat /etc/passwd | cut -d ':' -f 1) do echo "User: $user" done
|
arr=("apple" "banana" "cherry") for fruit in "${arr[@]}" do echo "Fruit: $fruit" done
|
Over files |
Over range with break |
Over range with step |
Over string |
for file in /path/to/directory/* do echo "Processing $file" done
|
for i in {1..10} do if [ "$i" -eq 5 ]; then break fi echo "Number $i" done
|
for i in {0..10..2} do echo "Number $i" done
|
string="hello" for char in $(echo $string | fold -w1) do echo "Character: $char" done
|
break and continue can be used
|
Special characters and variables
/ |
Root directory |
$HOME |
The current user's home directory |
. |
Current directory |
$PWD |
The current working directory |
~ |
Current user directory |
$PATH |
A list of directories separated by colons (:) where the system looks for executable files |
~username |
Directory of a user with username |
$USER |
The username of the user running the script |
.. |
Parent directory |
$HOSTNAME |
The hostname of the machine the script is running on |
$0 |
The name of the Bash script |
$RANDOM |
Returns a different random number each time is it referred to |
$1-$9 |
The first 9 arguments to the Bash script |
$SECONDS |
Number of seconds since the shell was started. Can be used to measure elapsed time of a script |
$# |
Number of arguments passed to Bash script |
$OLDPWD |
Previous directory |
$@ |
All the arguments supplied to the Bash script |
$LINENO |
Current line number in a script or shell. Used for debugging |
$? |
The exit status of the most recently run process |
$SHELL |
Path to the user's default shell |
$$ |
The process ID of the current script |
$UID |
User unique ID |
|
Arithmetics
let writes the result to a variable but doesn't print it. Used only for integers. |
|
|
|
|
|
|
|
|
|
|
|
|
expr returns the result and prints it. Spaces are important. Used only for integers. |
|
|
|
|
|
|
$(()) can also be used for arithmetics with integers only. |
|
|
|
|
|
|
bc is used for more complex calculations. It can deal with decimals as well. |
|
b=$(echo "10.5-2.3" | bc -l)
|
c=$(echo "sqrt(25)" | bc -l)
|
d=$(echo "2 ^ 3" | bc -l)
|
rounded_value=$(echo "scale=2; 10/3" | bc)
|
|
Shebang
#!/bin/bash |
#!/usr/bin/env bash |
Variables
|
Hello |
|
Hello |
|
45 |
MY_STR3=”Num value is $MY_NUM”
|
Num value is 45 |
MY_STR4='Num value is $MY_NUM'
|
Num value is $MY_NUM |
|
/etc |
MY_COMMAND=$(ls $MY_PATH)
|
result of ls /etc |
File tests
-d |
returns 0 if directory |
-f |
returns 0 if file |
-e |
returns 0 if exists |
-s |
returns 0 if file isn't empty |
-r |
returns 0 if file exists and permissions are granted (-w, -x are also possible) |
Use either test -flag argument or [ -flag argument ] format.
Use echo $? to get the result in bash cmd
String tests
|
returns 0 if strings are equal |
|
returns 0 if strings are not equal |
|
returns 0 if $a length is zero |
|
returns 0 if $a length is non-zero |
|
returns 0 if strings are equal |
|
returns 0 if strings are not equal |
|
returns 0 if $a is alphabetically greater than $b |
|
returns 0 if $a is alphabetically less than $b |
[[ "$FILENAME" == *.txt ]]
|
returns 0 if $FILENAME matches glob pattern |
[[ "Hello !!" =~ ^Hello[[:space:]].* ]]
|
returns 0 if string matches regex pattern |
White spaces are important.
Integers test
Within [ ] |
Within [[ ]] |
-eq |
== |
-ne |
!= |
-gt |
> |
-lt |
< |
-ge |
>= |
-le |
<= |
Decimals comparison
decimal1=3.14
decimal2=2.71
# Use bc to compare decimal numbers
result=$(echo "$decimal1 > $decimal2" | bc -l)
if [ "$result" -eq 1 ]; then
echo "$decimal1 is greater than $decimal2"
elif [ "$result" -eq 0 ]; then
echo "$decimal1 is equal to $decimal2"
else
echo "$decimal1 is less than $decimal2"
fi
|
Conditional structures
cmd1 || cmd2 |
run cmd1, if fails run cmd2 |
cmd1 && cmd2 |
run cmd1, if ok run cmd2 |
if [ $a -gt 5 ] && [ $b -eq 20 ]; then echo "a > 5 AND b=20" elif [ $b -lt 15 ] || [ $c -ge 30 ]; then echo "b<15 OR c>=30" elif ! [ $a -eq 10 ]; then echo "a!=10" else echo "None of the conditions met" fi
|
case $input in start|START) echo "Starting the process..." ;; stop|STOP) echo "Stopping the process..." ;; *) echo "Invalid option: $input" ;; esac
|
options=("START" "STOP") select opt in "$options[@]" do case $opt in START) echo "Starting the process..." ;; STOP) echo "Stopping the process..." ;; *) echo "Invalid option: $input" ;; esac done
|
|
|
Associative arrays
Declare an associative array |
|
Adding/appending an item |
fruits[apple]="red" fruits[banana]="yellow"
|
Reading an item |
echo "The apple is ${fruits[apple]}"
|
Changing an item value |
fruits[apple]="green"
|
Removing an item |
|
Looping through keys |
for key in "${!fruits[@]}"; do echo "$key" done
|
Looping through values |
for value in "${fruits[@]}"; do echo "$value" done
|
Looping through keys and values |
for key in "${!fruits[@]}"; do echo "$key: ${fruits[$key]}" done
|
Length of an associative array |
|
While/Until loops
While |
Until |
counter=1 while [ $counter -le 10 ] do echo $counter ((counter++)) done
|
counter=1 until [ $counter -gt 10 ] do echo $counter ((counter++)) done
|
While with reading from a file |
while IFS= read -r line; do echo "$line" done < filename.txt
|
Exporting env variables
printenv |
Print list of all env variables |
export VAR="Hello World" |
Create env variable (for current session only) |
echo 'export NEW_VAR="Hello World"' >> ~/.bashrc |
Create env variable for future sessions |
source ~/.bashrc |
Reload the shell startup file (required after changing the file with prev. command) |
export PATH=$PATH:newvalue |
Appending a value (for current session only) |
unset VAR |
Remove env variable |
Arrays
Explicit declaration |
|
Implicit creation |
my_array=(element1 element2 element3)
|
Read a single element |
|
Read all elements |
|
Changing an element |
my_array[1]=new_element
|
Appending an element |
|
Removing an element |
|
Length of an array |
|
Looping through an array |
for element in "${my_array[@]}"; do echo $element done
|
Sparce array |
declare -a sparse_array sparse_array[3]="Third Element" sparse_array[7]="Seventh Element" for index in "${!sparse_array[@]}"; do echo "Index $index: ${sparse_array[$index]}" done
|
ECHO and READ
|
Hello, World! |
echo -n "This is a " echo "single line."
|
This is a single line. |
echo -e "This is a\ttab\tseparated\ttext."
|
This is a tab separated text. |
echo -E "This is a\ttab\tseparated\ttext."
|
This is a\ttab\tseparated\ttext. |
|
reading into a variable |
|
reading into several variables |
|
reading into array (whitespace is the default delimiter) |
read -p "Enter your name: " name
|
reading with prompt |
read -sp “Password: “ password
|
reading with silent input and prompt |
|
reading with a limited number of characters |
|
reading with 5s timeout |
|