Skip to content

Instantly share code, notes, and snippets.

@FreekPaans
Created December 11, 2017 22:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FreekPaans/1ac738bccbb212ff5a840004377ea4c5 to your computer and use it in GitHub Desktop.
Save FreekPaans/1ac738bccbb212ff5a840004377ea4c5 to your computer and use it in GitHub Desktop.
bash function which generates a json based on arguments
#!/usr/bin/env bash
# Usage: make_event my-event test "hello world" -> {"name":"my-event","test":"hello world","unixtime":123}
make_event() {
if ! (( "$#" % 2)); then
echo "log_event expects an uneven number of arguments"
echo "Usage: $0 <event-name> [[<key> <val>]...]"
exit 1
fi
build_pairs() {
if [[ "$#" -eq 1 ]]; then
return
fi
echo --arg "var$1" "$2" --arg "val$1" \""$3"\" "$(build_pairs $(($1 + 1)) "${@:4}")"
}
build_pipeline() {
if [[ "$#" -eq 1 ]]; then
return
fi
echo ' | .[$'var$1'] = $'val$1 $(build_pipeline $(($1 + 1)) "${@:4}")
}
local PIPELINE=$(build_pipeline 0 "${@:2}")
local PAIRS=$(build_pairs 0 "${@:2}")
eval jq -c -n $PAIRS \
--arg name "$1" \
--arg unixtime "$(date +%s)" \
--arg formattedtime \"$(date)\" \' \
' . | .["name"] = $name ' \
' | .["unixtime"] = $unixtime ' \
' | .["formattedtime"] = $formattedtime ' \
"$PIPELINE"\' <<< "{}"
}
log_event() {
EVENT="$(make_event "$@")"
echo "$(date) BACKUP_EVENT|$EVENT"
if [[ ! -z "$EVENT_LOG" ]]; then
echo "$EVENT" >> "$EVENT_LOG"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment