Created
September 16, 2016 13:27
-
-
Save nulldatamap/d9d50fc2478d492d3aa37dc58f1f60b9 to your computer and use it in GitHub Desktop.
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 | |
HEAD_LENGTH=5 | |
TAIL_LENGTH=134 | |
declare -A db | |
db[version]="0.0.6" # Database values | |
db[navn]="Marco" | |
db[kage]="sandt" | |
function get { | |
if [[ $# -le 0 ]] | |
then | |
echo "Error: expected one or more key names" | |
exit 1 | |
fi | |
for key in $@ | |
do | |
value=${db[$key]} | |
if [[ -z $value ]] | |
then | |
echo "Error: Key '$key' not present." | |
exit 1 | |
fi | |
echo "$value" | |
done | |
} | |
function has { | |
if [[ $# -eq 0 ]] | |
then | |
echo "Error: expected one or more key names" | |
exit 1 | |
fi | |
keys=$@ | |
if [[ $1 == "all" ]] | |
then | |
keys=${db[@]} | |
fi | |
for key in $keys | |
do | |
if [[ -z ${db[$key]} ]] | |
then | |
echo "false" | |
else | |
echo "true" | |
fi | |
done | |
} | |
function update { | |
cat $0 | head -n $HEAD_LENGTH > $0.tmp | |
for key in ${!db[@]} | |
do | |
echo "db[$key]=\"${db[$key]}\"" >> $0.tmp | |
done | |
cat $0 | tail -n $TAIL_LENGTH >> $0.tmp | |
chmod u+x $0.tmp | |
mv $0.tmp $0 | |
} | |
function set { | |
if [[ $# -ne 2 ]] | |
then | |
echo "Error: expected just key and value" | |
exit 1 | |
fi | |
key=$1 | |
value=$2 | |
db[$key]="$value" | |
update | |
echo "ok" | |
} | |
function del { | |
if [[ $# -eq 0 ]] | |
then | |
echo "Error: expected keys" | |
exit 1 | |
fi | |
keys=$@ | |
if [[ $1 == "all" ]] | |
then | |
keys=${db[@]} | |
fi | |
for key in $keys | |
do | |
unset db[$key] | |
done | |
update | |
echo "ok" | |
} | |
function help { | |
echo "Commands:" | |
printf "\tget <keys..>\tReturns the values of the given keys\n" | |
printf "\thas <keys..>\tReturns whether the keys are present\n" | |
printf "\tset <key> <val>\tSets the given key to the given value\n" | |
printf "\tdel <keys..>\tDeltes the given keys\n" | |
} | |
case "$1" in | |
get) | |
get ${@:2} | |
exit $? | |
;; | |
has) | |
has ${@:2} | |
exit $? | |
;; | |
set) | |
set ${@:2} | |
exit $? | |
;; | |
del) | |
del ${@:2} | |
exit $? | |
;; | |
help) | |
help | |
exit $? | |
;; | |
*) | |
echo "Error: unknown command '$1', use 'db help'" | |
exit 1 | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment