Skip to content

Bash Scripting

Cheatsheet Bash scripting

Table of contents
  1. Cheatsheet Bash scripting
  2. Basics
  3. Variables
  4. Arrays
  5. Loops
  6. Conditionals
  7. References

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 terminal
    • echo Hello world! - prints ‘Hello world!’

Variables

  • COLOR="green" - create variable COLOR and set it to green, you can then use it such as:
    • echo $COLOR
    • echo "$COLOR"
    • echo "${COLOR}"
    • echo "My favourite color is $COLOR!"

Arrays

  • COLORS=("red", "green", "blue") - Define an array of colors
  • echo ${COLORS[0]} - Print first element in the array
  • echo ${COLORS[-1]} - Print last element in the array
  • echo ${COLORS[@]} - Prints all elements separated by a space
  • echo ${#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

References