2017-09-12 113 views
0

新的編程和需要一點幫助。bash循環mysql輸出多個變量

我需要訪問MySQL數據庫和環通的「名爲ftpuser」和「領域」行給我下面

echo 2>&1 " 3cmd put -r /home/$ftpuser/backups/ s3://bucket-backup/$domainname/" 

輸出,當我運行shell腳本,它下面的輸出以往用戶與每個域

3cmd put -r /home/user1/backups/ s3://bucket-backup/domain1.com/ 
3cmd put -r /home/user1/backups/ s3://bucket-backup/domain2.com 
3cmd put -r /home/user1/backups/ s3://bucket-backup/domain3.com/ 
3cmd put -r /home/user2/backups/ s3://bucket-backup/domain1.com/ 
3cmd put -r /home/user2/backups/ s3://bucket-backup/domain2.com/ 
3cmd put -r /home/user2/backups/ s3://bucket-backup/domain3.com/ 

結果即時尋找是

3cmd put -r /home/user1/backups/ s3://bucket-backup/domain1.com/ 
3cmd put -r /home/user2/backups/ s3://bucket-backup/domain2.com/ 
3cmd put -r /home/user3/backups/ s3://bucket-backup/domain3.com/ 
3cmd put -r /home/user4/backups/ s3://bucket-backup/domain4.com/ 

這裏是代碼

!/斌/慶典

filelines=username=$(mysql -h localhost -u root -p -ss -e "use users; SELECT ftpuser FROM users; ") 

filelines2=username=$(mysql -h localhost -u root -p -ss -e "use users; SELECT domain FROM users; ") 

echo Start 

for username in $filelines ; do 

for domainname in $filelines2 ; do 

echo 2>&1 " 3cmd put -r /home/$username/backups/ s3://bucket-backup/$domainname/" 

done 
done 

回答

0
商店

filelinesfilelines2在單獨的bash陣列和循環一次通過索引的元素,如圖所示。

arr1=($filelines) 
arr2=($filelines2) 
for i in ${!arr1[@]} 
do 
    echo 2>&1 " 3cmd put -r /home/${arr1[$i]}/backups/ s3://bucket-backup/${arr2[$i]}/" 
done 

輸出:

3cmd put -r /home/user1/backups/ s3://bucket-backup/domain1/ 
3cmd put -r /home/user2/backups/ s3://bucket-backup/domain2/ 
3cmd put -r /home/user3/backups/ s3://bucket-backup/domain3/ 
3cmd put -r /home/user4/backups/ s3://bucket-backup/domain4/ 

您可以參考Looping over arrays, printing both index and value理解的循環語法。

+0

工作很棒!謝謝。 –

+0

您好,歡迎您將此標記爲最佳答案。謝謝 –

+0

只是。再次感謝 –