BashファイルのMySQLクエリ

BashファイルのMySQLクエリ

複数の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

より良いアプローチは、/etc/mysql/my.cnfmysqlファイルにパスワードを設定して、毎回パスワードを入力する必要がないようにすることです。

[client]
password    = your_password

後者の場合は、前のスクリプトからパスワード関連の内容をすべて削除してください。

おすすめ記事