Created
May 5, 2014 22:49
-
-
Save kylemanna/0d2296d4f8c30f5c4958 to your computer and use it in GitHub Desktop.
Shell functions to wrap cmdline utility output with JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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