Get exit code of a background process

前端 未结 12 1865
别跟我提以往
别跟我提以往 2020-11-22 17:14

I have a command CMD called from my main bourne shell script that takes forever.

I want to modify the script as follows:

  1. Run the command CMD in parallel
12条回答
  •  眼角桃花
    2020-11-22 17:59

    A simple example, similar to the solutions above. This doesn't require monitoring any process output. The next example uses tail to follow output.

    $ echo '#!/bin/bash' > tmp.sh
    $ echo 'sleep 30; exit 5' >> tmp.sh
    $ chmod +x tmp.sh
    $ ./tmp.sh &
    [1] 7454
    $ pid=$!
    $ wait $pid
    [1]+  Exit 5                  ./tmp.sh
    $ echo $?
    5
    

    Use tail to follow process output and quit when the process is complete.

    $ echo '#!/bin/bash' > tmp.sh
    $ echo 'i=0; while let "$i < 10"; do sleep 5; echo "$i"; let i=$i+1; done; exit 5;' >> tmp.sh
    $ chmod +x tmp.sh
    $ ./tmp.sh
    0
    1
    2
    ^C
    $ ./tmp.sh > /tmp/tmp.log 2>&1 &
    [1] 7673
    $ pid=$!
    $ tail -f --pid $pid /tmp/tmp.log
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    [1]+  Exit 5                  ./tmp.sh > /tmp/tmp.log 2>&1
    $ wait $pid
    $ echo $?
    5
    

提交回复
热议问题