0

I wish to run a bash script that asks for a variable to be then used in a sqlite query.

I have no real experience in scripting, anyway I've tried something like the following but it doesn't work. Doesn't even give an error, just it doesn't show anything.

#!/bin/bash
echo name   
read name   
sqlite3 /arch.db << 'EOF'
.headers on
select type, number, address from documents where name = '$name';
EOF

I'd appreciate any help.

roaima
  • 107,089
  • 14
  • 139
  • 261
M.I.
  • 1
  • 1
  • 1
    Your query is looking to match against the literal five characters `$name`, not against the variable with the same name – roaima May 08 '21 at 16:10
  • This answer will help, https://unix.stackexchange.com/a/423446/100397, if not as a duplicate – roaima May 08 '21 at 16:13
  • 2
    Does this answer your question? [passing and setting variables in a heredoc](https://unix.stackexchange.com/questions/405250/passing-and-setting-variables-in-a-heredoc) – muru May 08 '21 at 16:35
  • I've tried $name ${name} "$name" "${name}" but none of them works.... – M.I. May 08 '21 at 16:43
  • 4
    @M.I. the quotes around `'EOF'` prevent expansion of the heredoc contents, regardless of any quoting used within it – steeldriver May 08 '21 at 17:59
  • Does this answer your question? [$VAR vs ${VAR} and to quote or not to quote](https://unix.stackexchange.com/questions/4899/var-vs-var-and-to-quote-or-not-to-quote) – roaima May 08 '21 at 21:25
  • Thanks a lot steeldriver, your suggestion helped me. – M.I. May 10 '21 at 07:11
  • The duplicate is not exactly the same question, but it has exactly the same issue, namely the quoting of a here-document that shouldn't be quoted. – Kusalananda Aug 16 '22 at 09:16

1 Answers1

-1

Before answering about your script: are you sure that the path is correct? This path: sqlite3 /arch.db means that arch.db is searched in the root /.

Perhaps you meant ./arch.db? So that the sqlite db file is looked in the same path of the script?

Please note that **the $name var is quoted in two ', that means that the variable is not treated as such, but as a string.

Your script could be rewritten in this way:

#!/bin/bash
echo name   
read name   
sqlite3 ./arch.db <<EOF
.headers on
select type, number, address from documents where name = "$name";
EOF
Francesco Colista
  • 1,347
  • 10
  • 21
  • The `<<'EOF'` correctly introduces a quoted here-document. There is nothing wrong with the quoting of `EOF` at the start of the here-document, other than the fact that it stops `$name` from being expanded. The single quotes around `$name` inside the here-document is just text, not shell syntax, so they have no meaning to the shell. Note that there is a huge difference between using single and double quotes in an SQL statement and that `"something"` refers to a column in a table, whereas `'something'` is a string. – Kusalananda Aug 16 '22 at 09:06