
我正在嘗試創建一個 bash 腳本來更改 MySQL root 密碼,以下是我正在使用的當前程式碼片段:
#!/bin/sh
clear
echo "Enter the current password for the root mysql account."
read oldrootpass
echo "Enter a new password for the root mysql account."
read newrootpass
mysql -u root -p$oldrootpass -Bse 'UPDATE user SET password=PASSWORD("$newrootpass") WHERE User="root"'
上面更改 root 密碼的語法可能不正確,但我所堅持的部分是產生一個與 mysql 一起使用的一行命令,如果該命令超過 2 行,則輸入 MySQL 提示符,並且在一旦使用“exit”命令關閉MySQL提示符,就會執行bash 腳本。
我的目的是透過bash腳本收集相關密碼訊息,運行單一命令來更改root密碼,然後返回bash腳本,或bash提示腳本已結束。
答案1
如果您詢問如何使用單一命令運行多個語句mysql
,您可以簡單地用分號分隔它們:
$ mysql -e 'select 1; select 2'
+---+
| 1 |
+---+
| 1 |
+---+
+---+
| 2 |
+---+
| 2 |
+---+
或者您可以建立一個包含 SQL 語句的檔案並執行:
$ mysql < change_password.sql
答案2
使用 mysqladmin 而不是在 mysql 中執行查詢。
mysqladmin -u root -p'$oldrootpass' password '$newrootpass'
應該可以,但你可能需要稍微修改一下引號。