shell_dump_function
To save piles of typing when debugging bash scripts, a dump() function that understands both regular and associative arrays:
is_array() { if [ -n "$BASH" ]; then declare -p ${1} 2> /dev/null | grep 'declare \-a' >/dev/null && return 0 fi return 1 } is_hash() { if [ -n "$BASH" ]; then declare -p ${1} 2> /dev/null | grep 'declare \-A' >/dev/null && return 0 fi return 1 } dump() { for var; do if is_array ${var} ; then echo ${var} = $(eval "echo \${${var}[@]}") elif is_hash ${var} ; then dump_hash ${var} else echo ${var} = $(eval "echo \$${var}") fi done } dump_hash() { h=${1} for k in $(eval "echo \${!${h}[@]}"); do echo "$h[${k}]" = $(eval "echo \${${h}[${k}]}") done }
First, it can dump regular variables:
$ dump HOME HISTFILE HISTSIZE HOME = /home/rpjday HISTFILE = /home/rpjday/.bash_history HISTSIZE = 1000 $
Next, dumping regular arrays:
$ people=(fred barney wilma betty) $ dump people people = fred barney wilma betty $
Finally, dump a bash associative array:
$ declare -A wife $ wife[fred]=wilma $ wife[barney]=betty $ dump wife wife[fred] = wilma wife[barney] = betty $
shell_dump_function.txt · Last modified: 2019/10/24 23:44 by rpjday