Execute multiple shell scripts concurrently

前端 未结 5 665
Happy的楠姐
Happy的楠姐 2020-12-15 08:56

I want to do the following things:

  • Execute multiple shell scripts (here 2 scripts) concurrently.

  • Wait until both scripts finish

5条回答
  •  有刺的猬
    2020-12-15 09:50

    Here is some code that I have been running, that seems to do exactly what you want. Just insert ./a.sh and ./b.sh where appropriate:

    # Start the processes in parallel...
    ./script1.sh 1>/dev/null 2>&1 &
    pid1=$!
    ./script2.sh 1>/dev/null 2>&1 &
    pid2=$!
    ./script3.sh 1>/dev/null 2>&1 &
    pid3=$!
    ./script4.sh 1>/dev/null 2>&1 &
    pid4=$!
    
    # Wait for processes to finish...
    echo -ne "Commands sent... "
    wait $pid1
    err1=$?
    wait $pid2
    err2=$?
    wait $pid3
    err3=$?
    wait $pid4
    err4=$?
    
    # Do something useful with the return codes...
    if [ $err1 -eq 0 -a $err2 -eq 0 -a $err3 -eq 0 -a $err4 -eq 0 ]
    then
        echo "pass"
    else
        echo "fail"
    fi
    

    Note that this captures the exit status of the script and not what it outputs to stdout. There is no easy way of capturing the stdout of a script running in the background, so I would advise you to use the exit status to return information to the calling process.

提交回复
热议问题