From c52aff468347f4372ee8dd46874158ff167215ef Mon Sep 17 00:00:00 2001 From: Will Woods Date: Jun 15 2020 23:46:30 +0000 Subject: sqlite2csv.sh: if there's only one table, dump that table Reworked sqlite2csv.sh so if the database only contains one table, it dumps that table. It also shouldn't create empty files if you mess up the filename. --- diff --git a/sqlite2csv.sh b/sqlite2csv.sh index 90e25de..4901ea0 100755 --- a/sqlite2csv.sh +++ b/sqlite2csv.sh @@ -1,11 +1,28 @@ #!/bin/sh -case $# in - 1) sqlite3 -csv "$1" ".tables" ;; - 2) sqlite3 -csv -header "$1" "SELECT * FROM $2" ;; - *) - echo "usage: sqlite2csv.sh DATABASE TABLENAME" - echo "omit TABLENAME to list table names." - exit 2 - ;; -esac +die() { echo "sqlite2csv.sh: $@" >&2; exit 1; } + +if [ $# = 0 ] || [ $# -gt 2 ]; then + echo "usage: sqlite2csv.sh DATABASE [TABLENAME]" + echo "TABLENAME is required if DATABASE contains multiple tables." + exit 2 +fi + +DATABASE="$1" +TABLENAME="$2" + +if [ ! -f "$DATABASE" ]; then + die "'$DATABASE' not found" +fi + +if [ ! -n "$TABLENAME" ]; then + set -- $(sqlite3 "$DATABASE" ".tables") + case $# in + 0) die "$DATABASE: no tables found" ;; + 1) TABLENAME="$*" ;; + *) die "need table name (one of: $*)" ;; + esac +fi + +sqlite3 -csv -header "$DATABASE" "SELECT * FROM $TABLENAME" +