0
mysql -u root -ppasswd -e"use test_db;"

The command can run in shell console without entering into mysql console.

Why the following two lines can't run in the shell console?

str="use test_db;"
mysql -u root -ppasswd -e$str;


ERROR 1049 (42000): Unknown database 'test_db;'

2 Answers 2

2

The issue here is that the shell is splitting your string, so your command ends up being this:

mysql -u root -ppasswd -euse test_db;

test_db; is interpreted as a separate argument, the name of a database.

To solve this problem, use quotes:

str="use test_db;"
mysql -u root -ppasswd -e"$str"

I removed the semicolon as it seems like you're specifying it twice. For a single command, I don't think you need it at all but I guess your script will be more complicated than this in reality.

As an aside, you can skip the use db_name command by specifying a database (as you were doing by accident):

str="select col1, col2 from table"
mysql -u root -ppasswd -e"$str" test_db
Sign up to request clarification or add additional context in comments.

Comments

1

Because shell split your string str. You should write like this:

mysql -u root -ppasswd -e"$str"

Or you will get this:

mysql -u root -ppasswd -euse test_db

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.