Skip to content

Instantly share code, notes, and snippets.

@kylemanna
Created May 5, 2014 22:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kylemanna/0d2296d4f8c30f5c4958 to your computer and use it in GitHub Desktop.
Save kylemanna/0d2296d4f8c30f5c4958 to your computer and use it in GitHub Desktop.
Shell functions to wrap cmdline utility output with JSON
#
# 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'
[ -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