Skip to content

Instantly share code, notes, and snippets.

@epochblue
Last active September 20, 2021 11:14
Show Gist options
  • Save epochblue/9982258 to your computer and use it in GitHub Desktop.
Save epochblue/9982258 to your computer and use it in GitHub Desktop.
A simple key-value "store" for use on the command line. Conceptually similar to Zach Holman's boom (https://github.com/holman/boom), but simpler and all in shell.
#!/usr/bin/env bash
# TODO: Document this
#
# AUTHOR: Bill Israel [https://github.com/epochblue]
# LICENSE: Public Domain
BOOMDB_DEFAULT="$HOME/.boomdb"
BOOMDB=${BOOMDB:=$BOOMDB_DEFAULT}
# Ensure the DB file exists
if [ ! -f $BOOMDB ]; then
touch $BOOMDB
fi
usage() {
echo "usage: $(basename $0) [OPTIONS] KEY
OPTIONS
-h, --help Print this message
-f, --find TERM Fuzzy-find a key matching the given term
-a, --add KEY CONTENTS Add a KEY to the database with the given contents
-d, --delete KEY Delete the given key
-v, --view KEY Show the CONTENTS for the given KEY
"
}
_boom_key_exists() {
name=$1
echo $(grep -c -e "^$name\t" $BOOMDB)
}
boom_all() {
boom_find
}
boom_find() {
args="$@"
cat $BOOMDB | grep -e "${args// /.}" | column -t -s$'\t'
}
boom_view() {
name=$1
found=$(_boom_key_exists $name)
if [ "$found" -eq 0 ]; then
echo "Error: No key found matching '$name'"
exit 1
else
grep -e "^$name\t" $BOOMDB | awk 'BEGIN {FS="\t"} {print $2}' | tr -d '\n'
fi
}
boom_copy() {
name=$1
found=$(_boom_key_exists $name)
if [ "$found" -eq 0 ]; then
echo "Error: No key found matching '$name'"
exit 1
else
boom_view $@ | pbcopy
echo "Copied $name to your clipboard."
fi
}
boom_delete() {
name=$1; shift
found=$(_boom_key_exists $name)
if [ "$found" -eq 0 ]; then
echo "Error: No key found matching '$name'"
exit 1
else
# What the actual fuck, OS X?
if [ "$(uname)" == "Darwin" ]; then
sed -i '' -e "/^$name /d" $BOOMDB
else
sed -i -e "/^name\t/d" $BOOMDB
fi
fi
}
boom_add() {
name=$1
content=$2
if [ -z "$content" ]; then
usage
exit 1
fi
found=$(_boom_key_exists $name)
if [ "$found" -eq 0 ]; then
echo -e "$name\t$content" >> $BOOMDB
else
echo "Error: Key name already in use, please choose another."
exit 1
fi
}
cmd=$1; shift
if [ -z $cmd ]; then
boom_all
else
case "$cmd" in
-h|--help)
usage
;;
-a|--add)
boom_add $@
;;
-d|--delete)
boom_delete $@
;;
-v|--view)
boom_view $@
;;
-f|--find)
boom_find $@
;;
*)
boom_copy $cmd
;;
esac
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment