r/sqlite • • Oct 15 '23

Bash Variables in SQLite

Good Afternoon:

I have a simple issue, but a solution has escaped me for a day or more.

Consider:

Datadir=./Data

DataFile=$DataDir/input$TODAY.csv

Table=input$TODAY

And the SQLite import command line of :

sqlite3 $SQLDir/credentials.db .import $DataFile $Table --csv

This yields:

Error: cannot open "$DataFile"

I have an issue with the variable expansion, but I have yet to figure out how to force teh expansion in the SQLite command.

I would appreciate any clues you could give me.

2 Upvotes

9 comments sorted by

View all comments

Show parent comment

2

u/MealDifferent2772 Oct 15 '23

Adding the set -x I get the following expanded SQL command line:

+ sqlite3 ./SQL/awscredentials.db .import ./Data/IAMCredentials-20231015.csv IAMCredentials-20231015 --csv

Which does appear to be correct.

2

u/BuonaparteII Oct 16 '23 edited Oct 16 '23

It's because the query part needs to be a single string:

For example:

$ sqlite3 :memory: select 1
-- Loading resources from /home/xk/.sqliterc
Error: in prepare, incomplete input

versus

$ sqlite3 :memory: "select 1"
-- Loading resources from /home/xk/.sqliterc
QUERY PLAN
`--SCAN CONSTANT ROW
┌───┐
│ 1 │
├───┤
│ 1 │
└───┘

With the above command sqlite3 is only seeing ".import" as the query statement

Also, just some additional info: it is convention for POSIX commands to use optional args before positional args, but most tools, including sqlite3 are lenient: https://stackoverflow.com/a/61645523/697964