How do you run multiple programs in parallel from a bash script?

前端 未结 15 1272
眼角桃花
眼角桃花 2020-11-22 06:31

I am trying to write a .sh file that runs many programs simultaneously

I tried this

prog1 
prog2

15条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 07:05

    I had a similar situation recently where I needed to run multiple programs at the same time, redirect their outputs to separated log files and wait for them to finish and I ended up with something like that:

    #!/bin/bash
    
    # Add the full path processes to run to the array
    PROCESSES_TO_RUN=("/home/joao/Code/test/prog_1/prog1" \
                      "/home/joao/Code/test/prog_2/prog2")
    # You can keep adding processes to the array...
    
    for i in ${PROCESSES_TO_RUN[@]}; do
        ${i%/*}/./${i##*/} > ${i}.log 2>&1 &
        # ${i%/*} -> Get folder name until the /
        # ${i##*/} -> Get the filename after the /
    done
    
    # Wait for the processes to finish
    wait
    

    Source: http://joaoperibeiro.com/execute-multiple-programs-and-redirect-their-outputs-linux/

提交回复
热议问题