Home · RSS · E-Mail · GitHub · GitLab · Twitter · Mastodon

Bash bits

first published:

Another post with stuff I can’t remember or might forget again 🤷‍♂️

» Bash shebang

Specify the explicit path:

1
#!/bin/bash

Let the environment decide:

1
#!/usr/bin/env bash

Explanation: Alec Bennett

» Fail fast … and more

Best added directly after the shebang.

1
2
3
4
set -o xtrace   # output every line which gets executed
set -o nounset  # fail if an unset variable is used
set -o errexit  # fail if a command exits with non-zero
set -o pipefail # fail if a command in a pipe fails

or in short:

1
set -xueo pipefail

Reference: GNU Bash Manual - the set builtin

» Exit code of last execution

Check with $? if the last executed program failed (0 = ok, everything else = failed)

1
echo $?

Examples:

1
2
> true; echo $?
0
1
2
> false; echo $?
1

» Constants

Use readonly. For example, a fixed array of OS names:

1
readonly systems=( windows linux darwin  )

Reference: Jeff Lindsay et al. - bashstyle

» Strings equal check

1
2
3
4
5
if [[ "$str1" == "$str2" ]]; then
    echo "Strings are equal"
else
    echo "Strings are not equal"
fi

Reference: tecadmin.net - Check if two strings are equal

» For Loops

1
2
3
4
5
readonly systems=( windows linux darwin  )

for system in "${systems[@]}"; do
    echo "system: $system"
done

Reference: Vivek Gite

» Loop until failure

1
while <command to execute> ; do :; done

Reference: nneonneo & Gurpreet Atwal




Home · RSS · E-Mail · GitHub · GitLab · Twitter · Mastodon