Bash Scripting
Cheatsheet

Cheatsheet Bash scripting
This cheatsheet will have more code snippets on how to do something in bash. It will be a bit different from some other cheatsheets where I show a list of commands.
Basics
echo- print text to the terminalecho Hello world!- prints ‘Hello world!’
Variables
COLOR="green"- create variableCOLORand set it to green, you can then use it such as:echo $COLORecho "$COLOR"echo "${COLOR}"echo "My favourite color is $COLOR!"
Arrays
COLORS=("red", "green", "blue")- Define an array of colorsecho ${COLORS[0]}- Print first element in the arrayecho ${COLORS[-1]}- Print last element in the arrayecho ${COLORS[@]}- Prints all elements separated by a spaceecho ${#COLORS[@]}- Prints the number of elements in the array
Loops
For loops:
for item in ${MYLIST[@]}; do
echo $item
done
for ((i=0; i < 10; i++)); do
echo $i
done
for i in {1..10}; do
echo "Iteration number: $i"
done
While loop:
while true; do
echo "HELLO!"
done
Conditionals
Conditionals follow the familiar if statements:
if [ $COLOR != "green" ]; then
echo "Your favourite color isn't green"
fi
You can use [[ ... ]] to get a status of 0 or 1 depending on the evaluation of the conditional expression inside [[]].
[[ -z STRING ]]- Empty string[[ -n STRING ]]- Not empty string[[ -e FILE ]]- File exists[[ -r FILE ]]- File is readable[[ -d PATH ]]- PATH is a directory[[ -w FILE ]]- File is writeable[[ -s FILE ]]- File size is larger than 0 bytes[[ -x FILE ]]- File is executable[[ STRING == STRING ]]- Both strings are equal[[ STRING != STRING ]]- Strings aren’t equal[[ STRING =~ STRING ]]- Test STRING against a regex pattern[[ NUM -eq NUM]]- Both numbers are equal[[ NUM -ne NUM ]]- Numbers aren’t equal[[ NUM -lt NUM ]]- First NUM is less than second NUM[[ NUM -le NUM ]]- First NUM is less or equal than second NUM[[ NUM -gt NUM ]]- First NUM is greater than second NUM[[ NUM -ge NUM ]]- First NUM is greater or equal than second NUM[[ ! EXPRESSION ]]- Not[[ EXPRESSION && EXPRESSION ]]- And[[ EXPRESSION || EXPRESSION ]]- Or