Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing sqlite3 query in bash

Tags:

bash

posix

sqlite

Executing in bash

sqlite3 database.db 'select * from databases'

gives me good output, but unfortunately when I would like to create a query from a variable sqlite3 doesn't want to cooperate.

For example:

cmd="select * from databases"
cmd1="sqlite3 database.db"
cmd2="'select * from databases'"
echo $($cmd1 \'$cmd\')
echo $($cmd1 '$cmd')
echo $($cmd1 $cmd)
echo $($cmd1 $cmd2)
echo `$cmd1 $cmd2`

None of above works. I would like to have a function which would execute just query like "select * from databases".

like image 855
J. Doe Avatar asked Oct 29 '25 14:10

J. Doe


2 Answers

Your trouble is word splitting. When you run this:

sqlite3 database.db $sql

The shell splits $sql to words. But sqlite3 expects the SQL command as a single parameter. To prevent word splitting, you must enclose $sql in double-quotes:

sqlite3 database.db "$sql"

If you want to store the sqlite3 database.db in a variable called cmd, you can, and write:

$cmd "$sql"

The shell will split $cmd to words, and in this case you want that. You want the shell to see the sqlite3 command, and another word database.db as the first argument. That's way we don't enclose $cmd in double-quotes.

like image 163
janos Avatar answered Oct 31 '25 03:10

janos


Let's try this approach:

cmd1="sqlite3 database.db"
cmd2="select * from databases"
$cmd1 "$cmd2"

I've just tried - it works for me: enter image description here

like image 29
Ivan Kovbas Avatar answered Oct 31 '25 02:10

Ivan Kovbas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!