A shell script can use sqlite3 to access a database and provide a simple user interface. The next script implements the previous address database with sqlite instead of a flat text file. It provides three commands:
- init: This is to create the database
- insert: This is to add a new row
- query: This is to select rows that match a query
In use, it would look like this:
$> dbaddr.sh init
$> dbaddr.sh insert 'Joe User' '123-1234' 'user@example.com'
$> dbaddr.sh query name Joe
Joe User
123-1234
user@example.com
The following script implements this database application:
#!/bin/bash
# Create a command based on the first argument
case $1 in
init )
cmd="CREATE TABLE address \
(name string, phone string, email string);" ;;
query )
cmd="SELECT name, phone, email FROM address \
WHERE $2 LIKE '$3';";;
insert )
cmd="INSERT INTO address (name, phone, email) \
VALUES ( '$2', '$3', '$4' );";;
esac
# Send the command to sqlite3 and reformat the output
echo $cmd | sqlite3 $HOME/addr.db | sed 's/|/\n/g'
This script uses the case statement to select the SQL command string. The other command-line arguments are replaced with this string and the string is sent to sqlite3 to be evaluated. The $1, $2, $3, and $4 are the first, second, third, and fourth arguments, respectively, to the script.