Differences

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

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
shell_dump_function [2019/10/24 09:28] rpjdayshell_dump_function [2019/10/24 23:44] (current) rpjday
Line 1: Line 1:
-To save piles of typing when debugging bash scripts, a dump() function that understands arrays:+To save piles of typing when debugging bash scripts, a dump() function that understands both regular and associative arrays:
  
 <code> <code>
Line 5: Line 5:
     if [ -n "$BASH" ]; then     if [ -n "$BASH" ]; then
         declare -p ${1} 2> /dev/null | grep 'declare \-a' >/dev/null && return 0         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     fi
     return 1     return 1
Line 10: Line 17:
  
 dump() { dump() {
-        for var; do +    for var; do 
-                if is_array ${var} ; then +        if is_array ${var} ; then 
-                        echo ${var} = $(eval "echo "'${'"${var}"'[@]}'+            echo ${var} = $(eval "echo \${${var}[@]}"
-                else +        elif is_hash ${var} ; then 
-                        echo ${var} = $(eval "echo \$${var}"+            dump_hash ${var} 
-                fi +        else 
-        done+            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
 +}
 </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> </code>
 +
 +Next, dumping regular arrays:
  
 <code> <code>
-A=(fred barney wilma betty) +people=(fred barney wilma betty) 
-$ dump ARR +$ dump people 
-ARR = fred barney wilma betty+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>
  • shell_dump_function.1571909338.txt.gz
  • Last modified: 2019/10/24 09:28
  • by rpjday