代码之家  ›  专栏  ›  技术社区  ›  user1980099

如何并行bash for循环

  •  0
  • user1980099  · 技术社区  · 4 年前

    如何让这个循环使用并行linux命令?
     func() {
         ssh -q $cn "systemctl restart ntpd"
     }
    
     
     for num in $(seq 30 40) ; do
        num_tmp=$(printf "%03d" $num)
        cn="node$num_tmp"    
        func
    done | parallel
    

    我试着在循环的末尾添加parallel,但它不起作用

    0 回复  |  直到 4 年前
        1
  •  1
  •   Mark Setchell    4 年前

    像这样也许:

    seq -f "%03G" 30 40 | parallel --dry-run 'ssh -q node{} "systemctl restart ntpd"'
    

    样本输出

    ssh -q node030 "systemctl restart ntpd"
    ssh -q node031 "systemctl restart ntpd"
    ssh -q node032 "systemctl restart ntpd"
    ssh -q node033 "systemctl restart ntpd"
    ssh -q node034 "systemctl restart ntpd"
    ssh -q node035 "systemctl restart ntpd"
    ssh -q node036 "systemctl restart ntpd"
    ssh -q node037 "systemctl restart ntpd"
    ssh -q node038 "systemctl restart ntpd"
    ssh -q node039 "systemctl restart ntpd"
    ssh -q node040 "systemctl restart ntpd"
    

    或者,如果您有bash v4或更新版本,它可以为您设置零填充:

    parallel --dry-run 'ssh -q node{} "systemctl restart ntpd"' ::: {030..040}
    
        2
  •  0
  •   Kaan    4 年前

    添加此“&”以结束func;

     .....
        cn="node$num_tmp"    
        func &
    done