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".
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.
Let's try this approach:
cmd1="sqlite3 database.db"
cmd2="select * from databases"
$cmd1 "$cmd2"
I've just tried - it works for me:

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