#!/bin/sh dbfile=vote.sq3 # データベースファイル query() { sqlite3 -cmd 'PRAGMA foreign_keys=ON' $dbfile "$@" } usage() { # 使用法の説明出力 cat<<-EOF Usage: Add record: $0 "Voter" OneOfCandidates Initialize Database: $0 -i List all records: $0 -l Show summation of price: $0 -s EOF } init() { # 初期化 rm -f $dbfile # ファイルを消せばゼロからの開始となる cat<<-EOF | query CREATE TABLE candidates(cand TEXT UNIQUE); INSERT INTO candidates VALUES('赤'); INSERT INTO candidates VALUES('青'); INSERT INTO candidates VALUES('黄'); CREATE TABLE ballotbox (voter TEXT UNIQUE, cand TEXT, FOREIGN KEY(cand) REFERENCES candidates(cand)); EOF } list() { query "SELECT * from ballotbox;" } summary() { query "SELECT cand,count(cand) cn FROM ballotbox GROUP BY cand ORDER BY cn DESC;" } while getopts hils i; do # 有効なオプションは h i l s のどれか case "$i" in i) init; exit ;; l) list ;; s) summary ;; *) usage; exit ;; # 上記以外のオプション(-h含む)なら用法出力 esac done shift $((OPTIND-1)) # getoptsを抜けたら必ずこれで引数を調整する if [ -n "$1" -a -n "$2" ]; then query "REPLACE INTO ballotbox values('$1', '$2');" fi