Tuesday, October 20, 2015

Shell script to run multiple programs in Linux

"Recently, I had a situation where I needed to execute multiple programs in Linux at the same time while redirecting their outputs to separated log files and wait for them to finish.
If you ever need to do something like that, I leave year the script that I used to accomplish that task:"

#!/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
 
Post source:  http://joaoperibeiro.com/execute-multiple-programs-and-redirect-their-outputs-linux/