1

When I execute a MySQL query from the shell script using value as variable, it shows

ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@gmail.com' at line 1

my code

#!/bin/bash

email='[email protected]'

# Checking - is the email already exists,
email_exists=$(mysql -u username -ppassword -e "SELECT id FROM db.user where email=$email;")

no problem when using inline (without using a variable).

FYI: I am using email as a variable because I need to reuse somewhere in code.

1
  • Eh? It is indeed a problem if you write that code inline. What you're generating is SELECT id FROM db.user WHERE [email protected] Commented Jul 29, 2020 at 11:46

2 Answers 2

1

Add single quotes around the string (inside your existing double quotes) to make it valid SQL:

email_exists=$(mysql -u username -ppassword -e "SELECT id FROM db.user where email='$email';")

That said, note that this is only safe at all when you control the string and are certain it doesn't contain any literal quotes inside its content. ([email protected] is safe, but [email protected]'; DROP TABLE db; -- ' would not be). Bill Kelwin's answer on "Injection proof SQL statements from command line" provides one way to avoid this pitfall.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @charles-duffy
1

Single-quotes and double-quotes are used in bash to escape certain characters, they are not used to signal a string. The single-quotes in your case will not be used in your mysql statement, therefore you get a syntax error (you don't have a string your mysql statement).

#!/bin/bash

[email protected]

# Checking - is the email already exists,
email_exists=$(mysql -u username -ppassword -e "SELECT id FROM db.user where email='$email';")

2 Comments

(BTW -- flagged my own instance of this answer -- preceding this by 9 seconds -- as community wiki on account of answering a known duplicate, which is contrary to guidance in the "Answer Well-Asked Questions" section of How to Answer and thus not behavior it's good practice to profit by).
Thanks @fancyPants, Working fine with and without using quotes in the variable declaration ([email protected]).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.