Cheatsheet

Bash Scripting

Cheatsheet Bash scripting

Table of Contents
  1. Basics
    1. Variables
    2. Arrays
    3. Loops
    4. Conditionals
  2. 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:

bash
1for item in ${MYLIST[@]}; do
2 echo $item
3done
bash
1for ((i=0; i < 10; i++)); do
2 echo $i
3done
bash
1for i in {1..10}; do
2 echo "Iteration number: $i"
3done

While loop:

bash
1while true; do
2 echo "HELLO!"
3done

Conditionals

Conditionals follow the familiar if statements:

bash
1if [ $COLOR != "green" ]; then
2 echo "Your favourite color isn't green"
3fi

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

Webmentions

0 Like 0 Comment

You might also like these

Cheatsheet for LunarVim

Read More
Cheatsheet

LunarVim

LunarVim

Cheatsheet for Docker

Read More
Cheatsheet

Docker

Docker

Cheatsheet for command line shortcuts

Read More
Cheatsheet

Command Line Shortcuts

Command Line Shortcuts

Cheatsheet for the editor VIM

Read More
Cheatsheet

Vim

Vim