Skip to content

Instantly share code, notes, and snippets.

@damouse
Created August 5, 2021 17:29
Show Gist options
  • Save damouse/b07e66472dd4c78a7dc08975f17389a2 to your computer and use it in GitHub Desktop.
Save damouse/b07e66472dd4c78a7dc08975f17389a2 to your computer and use it in GitHub Desktop.
Bash Array Cheatsheet
╔═════════════════╦════════════════════════════════════════╗
║ Syntax ║ Result ║
╠═════════════════╬════════════════════════════════════════╣
║ arr=() ║ Create empty array ║
║ arr=(1 2 3) ║ Initialize array ║
║ ${arr[2]} ║ Retrieve third element ║
║ ${arr[@]} ║ Retrieve all elements ║
║ ${!arr[@]} ║ Retrieve array indices ║
║ ${#arr[@]} ║ Calculate array size ║
║ arr[0]=3 ║ Overwrite 1st element ║
║ arr+=(4) ║ Append value(s) ║
║ str=$(ls) ║ Save ls output as string ║
║ arr=( $(ls) ) ║ Save ls output as array of files ║
║ ${arr[@]:s:n} ║ Elements at indices n to s+n ║
║ ${str//ab/c} ║ For a given string, replace ab with c ║
║ ${arr[@]//ab/c} ║ For each array item, replace ab with c ║
╚═════════════════╩════════════════════════════════════════╝
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment