'How to pass unix variable in where condition of query?

I have a file whose filename I am storing in a shell variable and I wish to pass that variable in the WHERE condition of my SQL select query. How can I achieve this ?

my code

cd /path/to/folder
var =$(ls tail)
id_var=$(echo "$var" | cut -f 1 -d '.')
...
...
sqlplus -s user/pwd@db < mysql.sql > output.txt

cat mysql.sql

select * from Records where "GlobalId"='$id_var'


Solution 1:[1]

From this answer:

cd /path/to/folder
var =$(ls tail)
id_var=$(echo "$var" | cut -f 1 -d '.')
sqlplus -s user/pwd@db @mysql.sql "${id_var}" > output.txt

Then in mysql.sql use &1 to substitute the first start argument:

select * from Records where "GlobalId"='&1'

Note: &1 is a substitution variable (and not a bind variable) so you will need to make sure that the value passed in does not perform any SQL injection attacks.

Solution 2:[2]

You can export the variable export id_var Then use envsubst command envsubst < mysql.sql

This will substitute your variable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MT0
Solution 2 Tanmay