Skip to content

Bash array json restic snapshots and jq

As you know bash is not ideal with multi arrays. Frequently I find myself wanting to read something like json into bash and loop over it. There are many ways to do this including readarray etc. I found this to work best for me. Note json can have lists so I collapse those with jq\'s join. Example:

# cat restic-loop-snaps.sh
#!/bin/bash

function loopOverArray(){

   restic snapshots --json | jq -r '.' | jq -c '.[]'| while read i; do
    id=$(echo $i | jq -r '.| .short_id')
    ctime=$(echo $i | jq -r '.| .time')
    hostname=$(echo $i | jq -r '.| .hostname')
    paths=$(echo $i | jq -r '. | .paths | join(,)')
    tagss=$(echo $i | jq -r '. | .tags | join(,)')
    printf %-10s - %-40s - %-20s - %-30s - %-20s\n $id $ctime $hostname $paths $tags
    done
}

loopOverArray

Run

# ./restic-loop-snaps.sh
0a71b5d4   - 2019-05-31T05:03:20.655922639-05:00      - pop-os               - /DATA/MyWorkDocs        -                     
...
Published inrestic