{"id":1431,"date":"2019-11-23T10:34:15","date_gmt":"2019-11-23T16:34:15","guid":{"rendered":"http:\/\/blog.ls-al.com\/?p=1431"},"modified":"2020-04-12T12:09:38","modified_gmt":"2020-04-12T17:09:38","slug":"bash-array-json-restic-snapshots-and-jq","status":"publish","type":"post","link":"https:\/\/blog.ls-al.com\/bash-array-json-restic-snapshots-and-jq\/","title":{"rendered":"Bash array json restic snapshots and jq"},"content":{"rendered":"
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:<\/p>\n
# cat restic-loop-snaps.sh\n#!\/bin\/bash\n\nfunction loopOverArray(){\n\n restic snapshots --json | jq -r '.' | jq -c '.[]'| while read i; do\n id=$(echo $i | jq -r '.| .short_id')\n ctime=$(echo $i | jq -r '.| .time')\n hostname=$(echo $i | jq -r '.| .hostname')\n paths=$(echo $i | jq -r '. | .paths | join(,)')\n tagss=$(echo $i | jq -r '. | .tags | join(,)')\n printf %-10s - %-40s - %-20s - %-30s - %-20s\\n $id $ctime $hostname $paths $tags\n done\n}\n\nloopOverArray<\/code><\/pre>\nRun<\/h3>\n# .\/restic-loop-snaps.sh\n0a71b5d4 - 2019-05-31T05:03:20.655922639-05:00 - pop-os - \/DATA\/MyWorkDocs - \n...<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"As you know bash is not ideal with multi arrays. Frequently I find myself wanting to read something like json<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[99],"tags":[],"class_list":["post-1431","post","type-post","status-publish","format-standard","hentry","category-restic"],"_links":{"self":[{"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/posts\/1431","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/comments?post=1431"}],"version-history":[{"count":0,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/posts\/1431\/revisions"}],"wp:attachment":[{"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/media?parent=1431"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/categories?post=1431"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.ls-al.com\/wp-json\/wp\/v2\/tags?post=1431"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}