Skip to content

Instantly share code, notes, and snippets.

@msuchodolski
Forked from magnetikonline/README.md
Created September 14, 2018 09:10
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msuchodolski/531da1ee9c2338dc7424fe004db74374 to your computer and use it in GitHub Desktop.
Save msuchodolski/531da1ee9c2338dc7424fe004db74374 to your computer and use it in GitHub Desktop.
Bash array usage cheatsheet.

Bash array usage cheatsheet

Create array

# 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 (seperate words)
$ echo "${myArray[@]}"

# all elements (single word, separated by first character of 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")

Get length

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

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

Iteration

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

Pass 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

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