2

Some helpful Bash bits

 2 years ago
source link: https://simjue.pages.dev/post/2022/bash-bits/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

first published: 2022-08-08

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

» Bash shebang

Specify the explicit path:

#!/bin/bash

Let the environment decide:

#!/usr/bin/env bash

Explanation: Alec Bennett

» Fail fast … and more

Best added directly after the shebang.

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

or in short:

set -euxo 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)

echo $?

Examples:

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

» Constants

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

readonly systems=( windows linux darwin  )

Reference: Jeff Lindsay et al. - bashstyle

» Strings equal check

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

readonly systems=( windows linux darwin  )

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

Reference: Vivek Gite


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK