bash循环mysql输出多个变量

时间:2017-09-12 02:30:39

标签: mysql bash shell loops variables

编程新手,需要一点帮助。

我需要访问一个MySQL数据库并通过'ftpuser'和'domain'列循环,以便给我输出

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

1 个答案:

答案 0 :(得分: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来了解循环语法。