Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active May 23, 2024 03:21
Show Gist options
  • Save magnetikonline/0ca47c893de6a380c87e4bdad6ae5cf7 to your computer and use it in GitHub Desktop.
Save magnetikonline/0ca47c893de6a380c87e4bdad6ae5cf7 to your computer and use it in GitHub Desktop.
Bash array usage cheatsheet.

Bash array usage cheatsheet

Creation

# empty
myArray=()

# with elements
myArray=("first" "second" "third item" "fourth")

myArray=(
  "first"
  "second"
  "third item"
  "fourth"
)

Get elements

# all elements - space delimited
$ echo ${myArray[@]}

# all elements - separate words
$ echo "${myArray[@]}"

# all elements - single word, separated by first character of IFS
$ IFS="-"
$ echo "${myArray[*]}"

# specific element
$ echo "${myArray[1]}"

# two elements, starting at second item
$ echo "${myArray[@]:1:2}"

# keys (indicies) of an array
$ echo "${!myArray[@]}"

Append element

myArray=()
myArray+=("item")

Array length

# element count
$ echo "${#myArray[@]}"

# length of specific element (string length)
$ echo "${#myArray[1]}"

Iteration

for arrayItem in "${myArray[@]}"; do
  echo "$arrayItem"
done

Pass array to function

Note

Named reference to another variable (local -n) only supported with Bash 4.3.x or above.

function myFunction {
  local -n givenList=$1
  echo "${givenList[@]}"
}

itemList=("first" "second" "third")
myFunction itemList

Reference

@pstephens
Copy link

Note: namerefs only work in bash 4.3.x... I've updated on my fork: https://gist.github.com/pstephens/7d7cfcdcf9f1e0a26f7ffba1e9399ef7/revisions

@magnetikonline
Copy link
Author

Thank you @pstephens - have updated 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment