To use MySQL or run MySQL queries from a shell script, you can use the mysql
command-line client. This client is included with the MySQL installation and allows you to connect to a MySQL server and execute SQL queries from the command line.
To use the mysql
client, you will need to provide your MySQL username and password. You can do this using the -u
and -p
options, respectively. For example:
mysql -u username -p
This will prompt you to enter your MySQL password. Once you enter the correct password, you will be connected to the MySQL server and will be able to execute SQL queries.
To execute a SQL query, you can simply type it at the MySQL prompt and press enter. For example:
mysql> SELECT * FROM users;
This will execute the SELECT
statement and display the results.
If you want to run MySQL queries from a shell script, you can use the mysql
command along with the -e
option, which allows you to specify a query to execute. For example:
mysql -u username -p -e "SELECT * FROM users;"
This will execute the SELECT
statement and display the results. You can also redirect the output to a file or pipe it to another command using shell redirection. For example:
mysql -u username -p -e "SELECT * FROM users;" > /path/to/output.txt
This will execute the SELECT
statement and save the results to the file /path/to/output.txt
.
You can also pass the password for the MySQL user as an argument to the -p
option, like this:
mysql -u username -p'password' -e "SELECT * FROM users;"
This will execute the SELECT
statement without prompting you to enter the password. However, this method is not recommended as the password will be visible in the command line history and may be exposed to other users on the system.