how do i loop from terminal without excessive password requests

我只是一个虾纸丫 提交于 2020-02-06 03:03:31

问题


When running the following mysql code from a linux (CentOS 7) terminal, the following command appears to be asking for the password for EVERY table in the loop. There are 500+ tables. It is not reasonable for me to type in a password 500+ times. How can I fix the code below so that it only asks for the password a couple times?

mysql -u root -p -Nse 'show tables' DATABASE_NAME | while read table; do mysql -u root -p -e "SET FOREIGN_KEY_CHECKS = 0; truncate table $table" DATABASE_NAME; done;  

EDIT:

Is there a way to do this without having to put the password in the command line logs?


回答1:


Put the password after the p (no space), say your password is PASSWORD

mysql -u root -pPASSWORD -Nse 'show tables' DATABASE_NAME | while read table; do mysql -u root -pPASSWORD -e "SET FOREIGN_KEY_CHECKS = 0; truncate table $table" DATABASE_NAME; done;



回答2:


Consider re-writing this, so that it only uses two database sessions. One to produce a list of statements to execute into a file, and second (single) to process the statements. There's potential for something to go wrong with the first query session, so I'd be careful to separate them into two tasks.

In the first session, suppress the formatting, and redirect stdout to a file

SELECT 'set foreign_key_checks = 0;' AS stmt

SELECT CONCAT('TRUNCATE TABLE `',t.table_schema,'`.`',table_name,'`;') AS stmt
  FROM information_schema.tables t
 WHERE t.table_schema = 'mydatabase'
 ORDER BY t.table_name ;

Verify that the file contains what you want.

Then (another useless use of cat) pipe the contents of that file into mysql

cat myfile | mysql -u me -p --database mydatabase


来源:https://stackoverflow.com/questions/27933828/how-do-i-loop-from-terminal-without-excessive-password-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!