Skip to content

Unix Shell

Dave Cox edited this page Aug 31, 2023 · 6 revisions

Get Version

/bin/bash --version

Arrays

Initialization

Just use parentheses around multiple values separated by spaces:

arr=(e1 e2 e3)
arr=("apple" "banana" "cherry")

Can also map to indices explicitly:

arr=([2]="apple" [3]="banana" [4]="cherry")

Print array values

echo ${arr[@]}

Diagnostic-friendly:

> declare -p dbFiles
declare -a dbFiles='([0]="~/Library/Application Support/scthost/aamfetch" [1]="~/Library/Application Support/scthost/aamfetch_*")'

Iterate array values

    for dbFile in "${dbFiles[@]}"; do
        # use $dbFile ...
    done

Capture Command Output in Array

Note that more simplistic approaches don't address parsing command output that contains spaces or wildcards. This approach is from https://www.baeldung.com/linux/reading-output-into-array, and works in Bash including older versions on macOS.
IFS=$'\n' read -r -d '' -a my_array < <( COMMAND && printf '\0' )
example:

    IFS=$'\n' read -r -d '' -a dbFiles < <(
            ls "$dbDir"/aamfetch "$dbDir"/aamfetch_* | grep -E "/aamfetch(_\d+)?$" &&                          \
            printf '\0')

Associative Arrays

Not Implemented in macOS Bash 3.2

Parameter Substitution

When variable is unset or null

https://tldp.org/LDP/abs/html/parameter-substitution.html
${parameter-default} If parameter is not set, use default.
${parameter:-default} If parameter is not set or is set to null, use default.

${parameter=default} If parameter not set, set it to default.
${parameter:=default} If parameter not set or is set to null, set it to default.

See above link for more

  • if parameter set, use alternate value
  • if param set, use it, else print error and abort
  • string length ${#var}.
  • remove patterns from front/back of var
  • substrings
  • substring/pattern replacement

Clone this wiki locally