How to execute a MySQL command from a shell script?

前端 未结 14 1178
生来不讨喜
生来不讨喜 2020-11-28 01:28

How can I execute an SQL command through a shell script so that I can make it automated?

I want to restore data I have collected in a SQL file using a shell script.

14条回答
  •  臣服心动
    2020-11-28 02:02

    The core of the question has been answered several times already, I just thought I'd add that backticks (`s) have beaning in both shell scripting and SQL. If you need to use them in SQL for specifying a table or database name you'll need to escape them in the shell script like so:

    mysql -p=password -u "root" -Bse "CREATE DATABASE \`${1}_database\`;
    CREATE USER '$1'@'%' IDENTIFIED BY '$2';
    GRANT ALL PRIVILEGES ON `${1}_database`.* TO '$1'@'%' WITH GRANT OPTION;"
    

    Of course, generating SQL through concatenated user input (passed arguments) shouldn't be done unless you trust the user input.It'd be a lot more secure to put it in another scripting language with support for parameters / correctly escaping strings for insertion into MySQL.

提交回复
热议问题