Reputation: 348
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;'
Upvotes: 0
Views: 28
Reputation: 108
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
Upvotes: 1
Reputation: 74595
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
Upvotes: 2