DevOps
bash
Jan 19, 2020     3 minutes read

1. What is bash and why would you use it?

2. Why am I writing this tutorial?

disclaimer: all the GNU/Linux/Unix systems I call Linux. I think it became a standard now. I know it’s incorrect (e.g. OSX), but shorter and everybody seems to understand ;)

skill but it is quite oldschool and sometimes daunting, especially because it probably is not you main programming language, as a developer. Even the simplest commands (if statements, assigning variables, executing commands, for loops) have rather non-intuitive, quirky syntax. This tutorial will hopefully serve me as a reference during future development.

3. Examples

shebang

Two possible ways:

#!/bin/bash
#!/usr/bin/env bash

The second one is more popular.

running code

There are at least three possible ways to execute a bash script:

variables assignment

x=10
var=hi
export var=hello
val=$(date)
var=$(ls | wc -l)

if statement

Keep in mind that you have to leave spaces between a condition inside square brackets and the brackets themselves:

if [ hi == hi ]
then
    echo yes
elif [ hi == hello ]
then
    echo no
else
    echo what
fi

A common practice is to write if [ hi == hi ]; then in one line.

Logical operators:

Check out this link for more detailed information.

for loop

There are many objects you can iterate over. You will find a pretty exhaustive list here with examples of break and continue. And here’s a trivial example:

for i in 1 2 3 4 5
do
   echo $i
done