简体   繁体   English

在Bash中使用参数循环遍历列表:如何?

[英]Looping through list with parameters in Bash: how?

This is more of a theoretical question, but let's say I have a master Rsync script that I'd like to use to backup multiple remote hosts to the same destination. 这更多是一个理论上的问题,但假设我有一个主要的Rsync脚本,该脚本可用于将多个远程主机备份到同一目标。

I'd like to have the script read a text file with each line containing hostname, source, destination, along the lines of this: 我想让脚本读取一个文本文件,其中每一行都包含主机名,源,目标以及以下内容:

host-one.example.com /Volumes/data /Volumes/host-one-backup
host-two.example.com /Volumes/Users /Volumes/host-two-backup
host-three.example.com /Volume/apps /Volumes/host-three-backup

And then a simple Rsync script that will pop in each of the three values accordingly, run that Rsync job, then go to the next, etc., within a looping script. 然后,一个简单的Rsync脚本将相应地弹出三个值中的每个值,运行该Rsync作业,然后转到循环脚本中的下一个,依此类推。

I'm good with everything except how to read the three values as variables within a script. 除了在脚本中如何将三个值作为变量读取之外,我对其他所有方面都很满意。

Your ideas or suggestions are most appreciated! 非常感谢您的想法或建议!

Cheers, Dan 干杯,丹

while read hostname source destination; do
    rsync -a "$hostname:$source" "$destination"
done < backup-list.txt

The cool/tricky part is treating the whole loop as a compound command and applying a redirection to it. 冷酷/棘手的部分将整个循环视为复合命令,并对其应用重定向。 This causes each read call to read a line from the file since stdin is redirected for the duration of the loop. 这会导致每个read调用都从文件中读取一行,因为在循环期间将重定向stdin。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM