Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-interactive SQLite3 usage from bash script

Tags:

bash

sqlite

I see plenty of examples showing how to use the sqlite3 interactive shell, e.g.:

$ sqlite3
$ sqlite3> SELECT * from x;

but I am looking for a way to create a table in a SQLite3 database with a bash script, aka, non-interactively.

For example, the following doesn't seem to work, it remains interactive:

#!/bin/bash
sqlite3 test.db  "create table n (id INTEGER PRIMARY KEY,f TEXT,l TEXT);"
sqlite3 test.db  "insert into n (f,l) values ('john','smith');"
sqlite3 test.db  "select * from n";
like image 916
Alexander Mills Avatar asked Feb 15 '17 09:02

Alexander Mills


People also ask

How do I read a .SQLite file in Linux?

If you are using Linux or a Mac, open a terminal window instead a command prompt. Open a command prompt (cmd.exe) and 'cd' to the folder location of the SQL_SAFI. sqlite database file. run the command 'sqlite3' This should open the SQLite shell and present a screen similar to that below.

What is difference between SQLite and sqlite3?

The wiki tag description for both tags is the same: SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. The sqlite3 has no synonyms but sqlite has sqlitedatabase as a solitary synonym.

How much traffic can SQLite handle?

The amount of web traffic that SQLite can handle depends, of course, on how heavily the website uses its database. Generally speaking, any site that gets fewer than a 100000 hits/day should work fine. The 100000 hits/day figure is a conservative estimate, not a hard upper bound.

How do I get out of SQLite in terminal?

Terminate the sqlite3 program by typing your system End-Of-File character (usually a Control-D). Use the interrupt character (usually a Control-C) to stop a long-running SQL statement.


2 Answers

While the above should work, I think it is better not to have to invoke sqlite3 multiple times, therefore I think the following is preferable:

#!/bin/sh
sqlite3 test.db <<EOF
create table n (id INTEGER PRIMARY KEY,f TEXT,l TEXT);
insert into n (f,l) values ('john','smith');
select * from n;
EOF

Note that unless you really need to use bash, you should prefer "/bin/sh" as your shebang, for portability reasons.

like image 88
varro Avatar answered Oct 19 '22 20:10

varro


Looks like it's as simple as

#!/bin/bash
sqlite3 test.db  "create table n (id INTEGER PRIMARY KEY,f TEXT,l TEXT);"
sqlite3 test.db  "insert into n (f,l) values ('john','smith');"
sqlite3 test.db  "select * from n;"

from https://mailliststock.wordpress.com/2007/03/01/sqlite-examples-with-bash-perl-and-python/

like image 40
Alexander Mills Avatar answered Oct 19 '22 20:10

Alexander Mills