Ling
Ling

Reputation: 25

docker run bash script cannot exit

In my CI system,jenkins execute shell script to build ... The script like this:

docker run -d --rm -v /code-path:/tmp docker-iamge-name sh -c " \
    cd /tmp ;\
    mkdir build ;\
    cd build ;\
    cmake ../ ;\
    make ;\
    ./unit-test-execute-file1 ;\
    ...
"

But when there are errors in code file, make command exits, and then next command(./unit-test-execute-file1) is executed. Since make failed, so unit-test-execute-file is not generated, and next command also fails... In the end, script exit with code 0, and Jenkins shows build is successful..

Can someone help? Thanks a lot!

Upvotes: 0

Views: 3414

Answers (2)

chepner
chepner

Reputation: 531460

Rather than rely on set -e (which really is not reliable, at least not without fully understanding all the exceptions that don't exit the shel), be explicit about which commands to run. In this case, you can simply chain the commands together with &&, so that each command only runs if the previous command succeeds. The exit status of the chain is the exit status of the last command to run (e.g., if cd build fails, its exit status is the exit status of sh -c).

docker run -d --rm -v /code-path:/tmp docker-iamge-name sh -c "
  cd /tmp &&
  mkdir build &&
  cd build &&
  cmake ../ &&
  make &&
  ./unit-test-execute-file1 &&
  ...
"

Upvotes: 1

Ayushya
Ayushya

Reputation: 10417

You should use set -e as the first line in the bash script if you want that script should exit at any point the script fails.

Your run statement would look like:

docker run -d --rm -v /code-path:/tmp docker-iamge-name sh -c " \
    set -e ;\
    cd /tmp ;\
    mkdir build ;\
    cd build ;\
    cmake ../ ;\
    make ;\
    ./unit-test-execute-file1 ;\
    ...
"

Upvotes: 1

Related Questions