mwrites
Web3 Cartographer

Web3 Cartographer

Bash Scripting Survival Guide

mwrites's photo
mwrites
·Jan 27, 2022·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Table of contents

  • Syntax
  • Flags
  • Bash Modes with set

Syntax

Check arguments Number

if [ $# -eq 0 ]; then
...
else
...
fi

Check variable exists

if [ -z ${$1+x} ]; then

Compare String

if [ "$1" = "$str2" ];

A Function

info () {
  echo -e "\n$1"
}

Calling a function

text="
************************
Uninstalling
************************
"

Flags

Skipping code with flags

while getopts :ab flag
do
    case "${flag}" in
        a) SKIP_INSTALL_A=1;;
        b) SKIP_INSTALL_B=1;;
    esac
done

if [ -z ${SKIP_INSTALL_A+x} ]; then
  echo "installing a stuff"
fi
./test.sh -p
./test.sh -pdt

Options with Arguments

while getopts s:n: flag
do
    case "${flag}" in
        s) some_string=${OPTARG};;
        n) some_number=${OPTARG};;
    esac
done
./test.sh -s SOME_STRING -n SOME_NUMBER

Bash Modes with set

Debug

set -x

Exit on command fail

set -e

Allow some commands to fail

set +e
or 
|| true

Exit on undeclared variables

set -u

Exit on piped command failed

set -o pipefail

Recap: Start your Sricrpt with this

set -euo pipefail
# set -x
 
Share this