Skip to content

Instantly share code, notes, and snippets.

@bahamas10
Last active March 3, 2019 15:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bahamas10/6828855 to your computer and use it in GitHub Desktop.
Save bahamas10/6828855 to your computer and use it in GitHub Desktop.
bash print array

parr

Print a bash array by name

This uses eval, as that is the only way to reference an array that has its name stored in a variable while retaining indices (for associative and sparse arrays). More info on why indirection won't work for this here http://mywiki.wooledge.org/BashFAQ/006#Evaluating_indirect.2Freference_variables

Note: the output generated by this function is NOT safe to eval by the shell, this is just meant to inspect the contents of array, like var_dump in PHP, or console.dir in JavaScript

$ a=([0]="hello" [1]="how are" [5]="you")
$ parr a
(
        [0]=`hello`
        [1]=`how are`
        [5]=`you`
)

This will also work for associative arrays in Bash >= 4

$ parr BASH_ALIASES
(
        [urldecode]=`python -c 'import sys;import urllib as u;print u.unquote_plus(sys.stdin.read());'`
        [basher]=`~/.basher/basher`
        [joyentstillpaying]=`sdc-listmachines | json -a -c "state !== 'running'" name state`
        [gerp]=`grep`
        [lsdisks]=`kstat -lc disk :::class | field 3 :`
        [ls]=`ls -p --color=auto`
        [cdir]=`cd "${_%/*}"`
        [urlencode]=`python -c 'import sys;import urllib as u;print u.quote_plus(sys.stdin.read());'`
        [cpp2c]=`sed -e 's#//\(.*\)#/*\1 */#'`
        [externalip]=`curl -s http://ifconfig.me/ip`
        [l]=`ls -CF`
        [lsnpm]=`npm ls -g --depth=0`
        [chomd]=`chmod`
)
parr() {
local key value name
for name in "$@"; do
echo '('
eval "
for key in \"\${!$name[@]}\"; do
value=\${$name[\$key]}
echo -e \"\\t[\$key]=\\\`\$value\\\`\"
done"
echo ')'
done
}
complete -A arrayvar parr
@bahamas10
Copy link
Author

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