Search code examples
bashsqlitevariablesclause

pass variable from bash into where clause of sqlite3


I want to pass that $period variable, as a condition in where clause of sqlite:

It will be in a form of:

-2 hours 
-1 day 

..or alike.

So it has blank space in it, and it gets into script through getopts,

./script.sh -p "-2 hours"

Then it gets parsed and sent to function, where I catch it as $1. But when trying to assemble it into that sqlite statement, in place of those ..., it does not work

period="$1"
sqlite3 -noheader domains.db "select domain,email,update_date,updated_on
                                from tbl_whois where last_run = 1 and updated_on > datetime('now', '...', 'localtime') limit $limit" | \

How would I be able to do that, tried with all possible cases of "" and '' but without success.

edit

just to be clear, variable gets fine, my problem is related to that space issue, as I get from SQlite, too many params specified, or error: near " ", because it obviously falls apart.


Solution

  • You can try:

    datetime('now', '$period', 'localtime')
    
    datetime('now $period', 'localtime')
    

    Or just

    datetime('$period', 'localtime')
    

    With those, $period would still expand since it's still a part of "". Those single quotes are considered literal values and would not affect it.