Home >Database >Mysql Tutorial >How Can I Safely Execute MySQL Commands with Passwords from Shell Scripts?
Executing MySQL Commands from Shell Scripts
Executing MySQL commands from shell scripts can be essential for automating database tasks. By incorporating MySQL commands into scripts, you can automate repetitive tasks or execute complex operations without manual intervention.
Problem Statement
A user wishes to execute the following MySQL command from a shell script:
mysql -h "server-name" -u root "password" "database-name" < "filename.sql"
This command restores data from a SQL file, but the user encounters an error when trying to execute it from a shell script.
Solution
The error arises when providing the password in the shell script. To specify a password in a shell script, use the -p flag with no space between the flag and the password, as shown below:
mysql -h "server-name" -u root "-pXXXXXXXX" "database-name" < "filename.sql"
Using a Configuration File for Credentials
An alternative approach is to store user credentials in the ~/.my.cnf file. This avoids the need to specify the password on the command line. The configuration file should have the following content:
[client] user = root password = XXXXXXXX
With the configuration file in place, the MySQL command can be executed as follows:
mysql -h "server-name" "database-name" < "filename.sql"
Troubleshooting Tips
If the MySQL command fails to execute from the shell script, consider the following troubleshooting tips:
The above is the detailed content of How Can I Safely Execute MySQL Commands with Passwords from Shell Scripts?. For more information, please follow other related articles on the PHP Chinese website!