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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #!/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 "" } |
#!/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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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" |
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.
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: Teaching Kids Programming - Island Shape Perimeter Algorithm
Next Post: Teaching Kids Programming - Find if Path Exists in Graph via Breadth First Search Algorithm