Search code examples
bashsqliteshellquoting

What is the proper quoting to assign an interpolated sqlite3 query to a variable in Bash?


I am trying to assign the output of the following to a variable

sqlite3 /home/user/db_fake_book_index "select id, page from fb2 where bookcode='$bookcode' and page=$page

If I run quote it like

echo "sqlite3 /home/user/db_fake_book_index \"select id, page from fb2 where bookcode='$bookcode' and page=$page\""

I get

sqlite3 /home/user/db_fake_book_index "select id, page from fb2 where bookcode='557S' and page=10"

and if I copy it to a console it works fine, but if i encase it in $() in my script it does not work, sqlite believes there are too many variables, it seems my double quotes are being removed.

$(printf "sqlite3 /home/user/db_fake_book_index \"select id, page from fb2 where bookcode='$bookcode' and page=$page\"")

This gives the same faliure


Solution

  • result=$( sqlite3 /home/user/db_fake_book_index "select id, page from fb2 where bookcode='$bookcode' and page=$page" )
    

    or

    query="select id, page from fb2 where bookcode='$bookcode' and page=$page"
    result=$( sqlite3 /home/user/db_fake_book_index "$query" )