Skip to main content

Arrays

We define arrays using parentheses:
To access an element by index:
The ${ } with the index in square brackets is the syntax for element access — different from regular variable access. We quote the whole expansion so its value stays one argument.

Arithmetic

Basic operators: +, -, *, /, % (modulus). We use $(( )) for arithmetic expressions:
Parameter expansion can also give us the length of a variable’s value:

tee

tee reads from stdin and writes to stdout and to a file at the same time. Useful when we want to see output on screen while also saving it to a file:

Loops

Bash has several loop forms. The three common list/condition forms below all use do / done. for — iterates over a list:
while — runs while the condition is true:
until — runs while the condition is false (the opposite of while):

case

case is for branching without chaining a long list of elif statements. We match a value against patterns and run the corresponding block:
A real example:
;; closes each branch. esac closes the whole block. The * pattern is the catch-all — anything that didn’t match above falls here. : is a command that does nothing successfully. If unknown values should terminate the whole script instead, we can use exit in that branch.