Created
June 26, 2019 14:25
-
-
Save brentd/9c29dd47db4d1085b9c50ab8f08d48df to your computer and use it in GitHub Desktop.
bashdb
This file contains hidden or 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
#!/bin/bash | |
DBNAME=${DBNAME:-database} | |
help() { | |
echo "A very lol key/value database written in bash. | |
usage: bashdb <command> <args> | |
get <key> Get a value from the database | |
set <key> <value> Set a value" | |
} | |
db_set() { | |
touch $DBNAME | |
local offset=$(( $(wc -c $DBNAME | tr -dc '0-9') + 1 )) | |
echo "$1,$2" >> $DBNAME | |
index_set $1 $offset | |
} | |
db_get() { | |
# If a byte offset is found in the index, seek to it and return the value | |
local offset=$(index_get "$1") | |
if [ -n "$offset" ]; then | |
echo $(tail -c +${offset} $DBNAME | get_value) | |
else | |
echo "Key not found" >&2 | |
exit 1 | |
fi | |
} | |
index_set() { | |
echo "$1,$2" >> "${DBNAME}_index" | |
} | |
index_get() { | |
echo $(grep "^$1," ${DBNAME}_index | get_value) | |
} | |
get_value() { | |
# Using , as a delimiter, split the input on the first occurrence and output the rest | |
IFS=',' read -r key value; echo $value | |
} | |
subcommand=$1 | |
case $subcommand in | |
"" | "-h" | "--help") | |
help | |
;; | |
*) | |
shift | |
db_${subcommand} "$@" | |
if [ $? = 127 ]; then | |
echo "Error: '$subcommand' is not a known subcommand." >&2 | |
exit 1 | |
fi | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment