From 58fa539d35079ad9bc3c59704b9dcf8a30ff7807 Mon Sep 17 00:00:00 2001 From: CyberLeo Date: Mon, 9 Jul 2012 06:26:20 -0500 Subject: [PATCH] sh/kvs: simple key-value store for shellscripts --- lib/sh/kvs.sh | 70 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 lib/sh/kvs.sh diff --git a/lib/sh/kvs.sh b/lib/sh/kvs.sh new file mode 100644 index 0000000..23cf6d8 --- /dev/null +++ b/lib/sh/kvs.sh @@ -0,0 +1,70 @@ +# Simple bourne shell based key-value store + +if [ -z "${__kvs_sh_loaded}" ] +then + __kvs_sh_loaded=yes + + t="$(printf '\t')" + + [ "${kvs}" ] || { + cat < "${kvs}" + + # Add or replace a value stored for a given key and id in the kvs + kvs_set() { + [ "${1}" -a "${2}" ] || return 255 + local id="${1}" + local var="${2}" + local val="${3}" + printf "%s\t%s\t%s\n" "${id}" "${var}" "${val}" >> "${kvs}" + } + + # Fetch the most recent value stored for a given key and id from the kvs + kvs_get() { + [ "${1}" -a "${2}" ] || return 255 + local id="${1}" + local var="${2}" + grep "^${id}${t}${var}${t}" "${kvs}" | tail -n 1 | cut -d"${t}" -f3- + } + + # Does the kvs have any entries for a given ID? + kvs_has_id() { + [ "${1}" ] || return 255 + local id="${1}" + grep -q "^${id}${t}" "${kvs}" + } + + # Does the kvs have a given key for a given ID? + kvs_has_key() { + [ "${1}" -a "${2}" ] || return 255 + local id="${1}" + local var="${2}" + grep -q "^${id}${t}${var}${t}" "${kvs}" + } + + # Remove a given key with a given ID from the kvs + kvs_unset() { + [ "${1}" -a "${2}" ] || return 255 + local id="${1}" + local var="${2}" + grep -v "^${id}${t}${var}${t}" "${kvs}" > "${kvs}.tmp" && mv -f "${kvs}.tmp" "${kvs}" || rm -f "${kvs}.tmp" + } + + # Remove all keys with a given ID from the kvs + kvs_unset_all() { + [ "${1}" ] || return 255 + local id="${1}" + grep -v "^${id}${t}" "${kvs}" > "${kvs}.tmp" && mv -f "${kvs}.tmp" "${kvs}" || rm -f "${kvs}.tmp" + } +fi -- 2.45.0