diff options
author | Julio Capote <jcapote@gmail.com> | 2023-01-24 03:20:47 +0000 |
---|---|---|
committer | Julio Capote <jcapote@gmail.com> | 2023-01-24 03:20:47 +0000 |
commit | f24f2d15275961f1c0144e68fde75a60aeaaa165 (patch) | |
tree | 38be1626f3ade436fbd17eadb2753fa2f0effb37 /content/post/2012-10-07-an-embedded-key-value-store-for-shell-scripts.markdown | |
parent | bf04383b34c4a4fdfe239de2805a30a051921002 (diff) | |
download | capotej.com-f24f2d15275961f1c0144e68fde75a60aeaaa165.tar.gz |
move to bear theme
Diffstat (limited to 'content/post/2012-10-07-an-embedded-key-value-store-for-shell-scripts.markdown')
-rw-r--r-- | content/post/2012-10-07-an-embedded-key-value-store-for-shell-scripts.markdown | 76 |
1 files changed, 0 insertions, 76 deletions
diff --git a/content/post/2012-10-07-an-embedded-key-value-store-for-shell-scripts.markdown b/content/post/2012-10-07-an-embedded-key-value-store-for-shell-scripts.markdown deleted file mode 100644 index 99180b3..0000000 --- a/content/post/2012-10-07-an-embedded-key-value-store-for-shell-scripts.markdown +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: "An Embedded Key/Value Store for Shell Scripts" -date: 2012-10-07T10:06:00Z -comments: true -tags: ['shell scripting', 'databases'] ---- - -UPDATE: this is now available as a [sub](http://github.com/37signals/sub) command, here: [kiev](http://github.com/capotej/kiev) - -Cooked this up last night when I needed a simple key/value store for use in a shell script: - -<!--more--> - -```sh db.sh -#!/bin/sh - -DBFILE=example.db - -put(){ - echo "export kv_$1=$2" >> $DBFILE -} - -del(){ - echo "unset kv_$1" >> $DBFILE -} - -get(){ - source $DBFILE - eval r=\$$(echo "kv_$1") - echo $r -} - -list(){ - source $DBFILE - for i in $(env | grep "kv_" | cut -d= -f1 ); do - eval r=\$$i; echo $(echo $i | sed -e 's/kv_//') $r; - done -} - -## cmd dispatch - -if [ ${1:-0} == "set" ]; then - put $2 $3 -elif [ ${1:-0} == "get" ] ; then - get $2 -elif [ ${1:-0} == "list" ] ; then - list -elif [ ${1:-0} == "del" ] ; then - del $2 -else - echo "unknown cmd" -fi -``` - -Use it like so: - - -`$ ./db.sh set foo bar` - -`$ ./db.sh get foo` - -`$ ./db.sh set foo baz` - -`$ ./db.sh get foo` - -`$ ./db.sh del foo` - -`$ ./db.sh list` - - -## How it works - -Every time you update/set/delete a value, it writes a shell expression to an append-only log, -exporting a shell variable (key) with that value. By sourcing the file every time we read a value, we -replay the log, bringing our environment to a consistent state. Then, reading the value is just looking -up that dynamic variable (key) in our shell environment. |