Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
shell_dump_function [2019/10/24 08:26] – created rpjdayshell_dump_function [2019/10/24 23:44] (current) rpjday
Line 1: Line 1:
-To save piles of typing when debugging scripts:+To save piles of typing when debugging bash scripts, a dump() function that understands both regular and associative arrays:
  
 <code> <code>
-dump ()  +is_array() { 
-{  +    if [ -n "$BASH" ]; then 
-    for v in "$@"; +        declare -p ${1} 2> /dev/null | grep 'declare \-a' >/dev/null && return 0 
-    do +    fi 
-        eval "echo ${v} = \$${v}";+    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     done
 } }
 </code> </code>
  
-Then:+First, it can dump regular variables:
  
 <code> <code>
-$ dump PATH HOME +$ dump HOME HISTFILE HISTSIZE
-PATH = /home/rpjday/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/local/go/bin:/home/rpjday/bin:/home/rpjday/go1.11.4/go/bin+
 HOME = /home/rpjday HOME = /home/rpjday
 +HISTFILE = /home/rpjday/.bash_history
 +HISTSIZE = 1000
 +$
 +</code>
 +
 +Next, dumping regular arrays:
 +
 +<code>
 +$ people=(fred barney wilma betty)
 +$ dump people
 +people = fred barney wilma betty
 +$
 +</code>
 +
 +Finally, dump a bash associative array:
 +
 +<code>
 +$ declare -A wife
 +$ wife[fred]=wilma
 +$ wife[barney]=betty
 +$ dump wife
 +wife[fred] = wilma
 +wife[barney] = betty
 +$
 </code> </code>
  • shell_dump_function.1571905564.txt.gz
  • Last modified: 2019/10/24 08:26
  • by rpjday