The Simplest Database Implementation by BASH Programming

in blurt •  3 years ago 

The following is probably the simplest Database implementation using BASH programming language. The BASH database provides four basic functions: db_clear() to truncate the database. The db_set() takes two parameters key and value which puts an entry key=value in the database. db_get() takes a parameter "key" that will retrieve the value for the entry "key". And the db_remove to remove an entry from the database.

#!/bin/bash

DATABASE_FILE=.database

function db_clear() {
  rm -f "$DATABASE_FILE"
}

function db_set() {
  echo "$1,$2" >> "$DATABASE_FILE"
}

function db_get() {
  grep "^$1," "$DATABASE_FILE" | sed -e "s/^$1,//" | tail -n 1
}

function db_remove() {
  db_set $1 ""
}

The underlying storage for the database is a plain text file (namely specified in variable DATABASE_FILE) where each entry is stored per line. The value for same entry key will be searched using the grep, sed and tail command so that only the latest value will be retrieved.

Example usages:

db_clear

db_set key key1
# key=key1
echo key=$(db_get key)  

db_set key key2
# key=key2
echo key=$(db_get key)

db_set name helloacm
db_set age 20

# name=helloacm
echo name=$(db_get name)
# age=20
echo age=$(db_get age) 
# 404=
echo 404=$(db_get 404)

echo DATBASE contents
# key,key1
# key,key2
# name,helloacm 
# age,20
cat "$DATABASE_FILE"

Removing an entry is the same as appending a "key," to the database file so that the latest value for the key will be NULL.

Reposted to Blog

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

Important Update of Delegation Service!

  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!
Sort Order:  

Congratulations! This post has been upvoted by the @blurtcurator communal account,
You can request a vote every 12 hours from the #getupvote channel in the official Blurt Discord.Don't wait to join ,lots of good stuff happening there.