< up >
2024-07-23

Bash - cheat sheet

Contents

Arguments

variable description
$0 name of the script
$1 first argument
$2 second argument
$<n> <nth> argument, where n > 0
$@ all arguments as one string
$# count of arguments

Example

#!/bin/bash

echo script started with $# args: $@

for arg in "$@"; do
    echo "$arg"
done
# $ ./script.sh --config=test --verbose 1 2
# script started with 4 args: --config=test --verbose 1 2
# --config=test
# --verbose
# 1
# 2

Conditionals

if [[ <CONDITION> ]]; then
  ...
elif [[ <CONDITION> ]]; then
  ...
else
  ...
fi
condition description
"$VAR" == "STRING" compare content of env var with string
-z "$VAR" test if string length is zero
-n "$VAR" test if string length is not zero
-f "$VAR" test if regular file exist