我想執行多個 MySQL 查詢並將它們儲存到指定的檔案中。查詢保存在 bash 腳本中,queries.sh
例如:
cat queries.sh
mysql -u <user> -p <DBname> -e "select Col1 from Table1 where Condition;" > /home/<user>/queries/Col1Table1Cond
mysql -u <user> -p <DBname> -e "select Col5 from Table2 where Condition;" > /home/<user>/queries/Col5Table2Cond
執行腳本是不夠的,因為<user>
必須在每次查詢時輸入密碼,這會損害腳本流程。
答案1
嘗試這個 ;)
user="jonnDoe"
dbname="customers"
password="VerySecret"
mysql -u $user -D $dbname -p $password -e "select Col1 from Table1 where Condition;" > /home/$user/queries/Col1Table1Cond
mysql -u $user -D $dbname -p $password -e "select Col5 from Table2 where Condition;" > /home/$user/queries/Col5Table2Cond
更好的做法是在 mysql/etc/mysql/my.cnf
檔案中配置密碼,這樣就不需要每次都輸入:
[client]
password = your_password
在後一種情況下,從先前的腳本中刪除所有與密碼相關的內容
答案2
通常有幾種不同的方法可以實現這一目標。
將其儲存在僅包含密碼的外部文件中:
$cat password.txt
Password
$cat queries.sh
mysql -u <user> -p$(cat password.txt) <rest of the command>
將其儲存在另一個 shell 腳本中:
$cat settings.sh
PASSWORD=Password
$cat queries.sh
source settings.sh
mysql -u <user> -p"$PASSWORD" <rest of the command>
將其儲存在名為 PASSWORD 的環境變數中:
$cat queries.sh
mysql -u <user> -p"$PASSWORD" <rest of the command>