Skip to content

Instantly share code, notes, and snippets.

@mutovkin
Created April 29, 2024 19:33
Show Gist options
  • Save mutovkin/d0d22697f9697bd9438eca7e3d64cc33 to your computer and use it in GitHub Desktop.
Save mutovkin/d0d22697f9697bd9438eca7e3d64cc33 to your computer and use it in GitHub Desktop.
Run query on top of SQLite database and output results to CSV
#!/usr/bin/env bash
# Script accepts 3 parameters
# 1. Query string to execute (in quotes which are opposite of quotes used in the query)
# 2. Database filename where the query will be executed
# 3. Output filename where the query result will be saved
QUERY_STRING=$1
DB_FILE=$2
OUTPUT_FILE=$3
# Check if the first argument is a query string
if [ -z "${QUERY_STRING}" ]; then
echo "Usage: query_to_csv.sh <query_string> <db_file> <output_file>"
exit 1
fi
# Check if the second argument is a db file
if [ -z ${DB_FILE} ]; then
echo "Usage: query_to_csv.sh <query_string> <db_file> <output_file>"
exit 1
fi
# check if filename ends with .db
if [[ ${DB_FILE} != *.db ]]; then
echo "Error: ${DB_FILE} is not a db file."
exit 1
fi
# Check if the db file exists
if [ ! -f ${DB_FILE} ]; then
echo "Error: ${DB_FILE} does not exist."
exit 1
fi
# Check if the third argument is an output file
if [ -z ${OUTPUT_FILE} ]; then
echo "Usage: query_to_csv.sh <query_string> <db_file> <output_file>"
exit 1
fi
# Check if the sqlite3 command exists
if ! command -v sqlite3 &> /dev/null; then
echo "Error: sqlite3 command was not found."
exit 1
fi
# Execute the query and save the result to the output file
sqlite3 ${DB_FILE} <<EOS
.mode csv
.headers on
.once ${OUTPUT_FILE}
${QUERY_STRING}
EOS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment