]> CyberLeo.Net >> Repos - CDN/shlib.git/blob - lib/sh/kvs.sh
sh/kvs: simple key-value store for shellscripts
[CDN/shlib.git] / lib / sh / kvs.sh
1 # Simple bourne shell based key-value store
2
3 if [ -z "${__kvs_sh_loaded}" ]
4 then
5   __kvs_sh_loaded=yes
6
7   t="$(printf '\t')"
8
9   [ "${kvs}" ] || {
10     cat <<EOF
11 KVS v0.1
12 Copyright - http://wiki.cyberleo.net/wiki/CyberLeo/COPYRIGHT?version=4
13
14 Set the following variables before sourcing this library:
15
16  kvs  - Path and filename of the kvdb database file
17 EOF
18     kill -ABRT $$
19     exit 1
20   }
21
22   [ -s "${kvs}" ] || echo "${t}${t}# KVSv0 id-key-value database" > "${kvs}"
23
24   # Add or replace a value stored for a given key and id in the kvs
25   kvs_set() {
26     [ "${1}" -a "${2}" ] || return 255
27     local id="${1}"
28     local var="${2}"
29     local val="${3}"
30     printf "%s\t%s\t%s\n" "${id}" "${var}" "${val}" >> "${kvs}"
31   }
32
33   # Fetch the most recent value stored for a given key and id from the kvs
34   kvs_get() {
35     [ "${1}" -a "${2}" ] || return 255
36     local id="${1}"
37     local var="${2}"
38     grep "^${id}${t}${var}${t}" "${kvs}" | tail -n 1 | cut -d"${t}" -f3-
39   }
40
41   # Does the kvs have any entries for a given ID?
42   kvs_has_id() {
43     [ "${1}" ] || return 255
44     local id="${1}"
45     grep -q "^${id}${t}" "${kvs}"
46   }
47
48   # Does the kvs have a given key for a given ID?
49   kvs_has_key() {
50     [ "${1}" -a "${2}" ] || return 255
51     local id="${1}"
52     local var="${2}"
53     grep -q "^${id}${t}${var}${t}" "${kvs}"
54   }
55
56   # Remove a given key with a given ID from the kvs
57   kvs_unset() {
58     [ "${1}" -a "${2}" ] || return 255
59     local id="${1}"
60     local var="${2}"
61     grep -v "^${id}${t}${var}${t}" "${kvs}" > "${kvs}.tmp" && mv -f "${kvs}.tmp" "${kvs}" || rm -f "${kvs}.tmp"
62   }
63
64   # Remove all keys with a given ID from the kvs
65   kvs_unset_all() {
66     [ "${1}" ] || return 255
67     local id="${1}"
68     grep -v "^${id}${t}" "${kvs}" > "${kvs}.tmp" && mv -f "${kvs}.tmp" "${kvs}" || rm -f "${kvs}.tmp"
69   }
70 fi