A Shell tool: jsondiff.sh Using the basic tutorial

  

I recently busy refactoring a history project, but due to objective conditions, no test cases are available, so I have to compare the result set of the old and new servers through human flesh. Consistent to judge right or wrong. Since laziness is the virtue of a programmer, I want to write a tool, and the result set is JSON, so I have jsondiff.sh.


The logic is very simple, nothing more than to get the result set on different servers through curl, and then diff, but there are a few points to note here: First, JSON is a line. Direct diff will lose meaning; secondly, Chinese characters in JSON will be encoded, which is not conducive to viewing; in addition, the order of fields in JSON is indifferent, so it is best to sort before diff. Explain that when formatting JSON data, I didn't use Bash, but instead used PHP
:

#!/bin/bashRM=/bin/rmPHP=/usr/bin /phpCURL=/usr/bin/curlDIFF=/usr/bin/diffVIMDIFF=/usr/bin/vimdiffCOLORDIFF=/usr/bin/colordiffusage() { echo "Usage: $0 --uri=<URI> --old =<IP> --new=<IP>"}format() { $PHP -R ' function ksort_recursive(&$array) { if (!is_array($array)) { return; } ksort($ Array); foreach (array_keys($array) as $key) { ksort_recursive($array[$key]); } } $options = JSON_PRETTY_PRINT |
  JSON_UNESCAPED_UNICODE; $array = json_decode($argn, true); ksort_recursive($array); echo json_encode($array, $options); '}request() { $CURL -s -H "Host: $1" " Http://$2$3"}eval set -- $( getopt -q -o "h" -l "host:,uri:,old:,new:,vim,help" -- "$@ ")while true; do case "$1" in --host) HOST=$2; shift 2;; --uri) URI=$2; shift 2;; --old) OLD=$2; shift 2;; --new) NEW=$2; shift 2;; --vim) VIM="Y"; shift 1;; -h|
 --help) usage; exit 0;; --) break;; esacdoneif [[ -z "$URI" |
 |
  -z "$OLD" |
 |
  -z "$NEW" ]]; then usage exit 1fiif [[ -z "$HOST" ]]; then HOST="www.foobar.com"fiOLD_FILE=$(mktemp)NEW_FILE=$(mktemp)request "$HOST" "$OLD" "$URI" |
  Format > $OLD_FILErequest "$HOST" "$NEW" "$URI" |
  Format > $NEW_FILEif [[ "$VIM" == "Y" ]]; then $VIMDIFF $OLD_FILE $NEW_FILEelif [[ -x "$COLORDIFF" ]]; then $COLORDIFF -u $OLD_FILE $NEW_FILEelse $ DIFF -u $OLD_FILE $NEW_FILEfi$RM -f $OLD_FILE$RM -f $NEW_FILE

The usage of "getopt" is worth noting. The related references are as follows:

  • Getopt in Bash< Br>
  • Bash: Preserving Whitespace Using set and eval

    When using, a variety of tools are allowed. By default, "colordiff" will be used first. If necessary, vimdiff can be activated. "." Not long after this article was written, I found a good tool "jq" for parsing JSON from the command line. If you know it can save a lot of time, just practice writing the shell.

  • Copyright © Windows knowledge All Rights Reserved