Skip to content

Instantly share code, notes, and snippets.

@kmanna
Forked from kylemanna/json_cmd.sh
Created May 7, 2014 00:13
Show Gist options
  • Save kmanna/39ef5f2f176f339baad6 to your computer and use it in GitHub Desktop.
Save kmanna/39ef5f2f176f339baad6 to your computer and use it in GitHub Desktop.
#
# Shell functions to wrap cmdline utility output with JSON
#
# Useful for running shell commands and then extracting output with logstash
#
json_kv_pair()
{
K="$1" # key
V="$2" # value
Q="$3" # quote
T="$4" # term
echo -n " \"$K\":$Q"
echo -n "$V" | sed -e 's/"/\\\"/g' -e ':a;N;$!ba;s/\n/\\n/g' -e 's/\t/\\t/g'
[ -z "$T" ] && echo -n "$Q," || echo -n "$Q"
}
json_kv_int() { json_kv_pair "$1" "$2" "" "$3"; }
json_kv_str() { json_kv_pair "$1" "$2" '"' "$3"; }
json_wrap_cmd()
{
CMD="$1"
echo -n "{"
json_kv_int "timestamp_start" "$(date +%s)"
json_kv_str "cmd" "$CMD"
OUT=$(echo "$CMD" | sh 2>&1)
RET=$?
DONE=$(date +%s)
json_kv_str "output" "$OUT"
json_kv_int "ret" "$RET"
json_kv_int "timestamp_stop" "$DONE" true
# TODO break-up stderr and stdout
echo " }"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment