[Jenkins] Jenkins 上的 shell script 執行錯誤就停止?

[Jenkins] Jenkins 上的 shell script 執行錯誤就停止?

今天在查 Jenkins 遇到的一個問題…

我們在 Jenkins 的工作裡,執行了一段 shell script (假設是 A),

而這段 shell script 會在修改某個 B 檔案後,再去執行另一個 C.sh 檔案,

執行完後,再把 B 檔案還原。

 

原本這個流程沒什麼問題,可是今天遇到一個怪現象,

就是 C.sh 執行失敗 (exit 傳回非零值) 後,

B 檔案沒有被還原,感覺上是 script 整個結束了,

但這和我們的預期不同…

 

來舉個例子吧~

假設有個 test1.sh 內容如下:

#!/bin/sh
echo 1
./test2.sh
echo after 2

 

而 test2.sh 內容如下:

#!/bin/sh
echo 2
exit 1

 

如果我執行 ./test1.sh,會依序印出 “1”, “2”, “after 2″,

結果符合我的預期:

testuser@localhost ~ $ ./test1.sh
1
2
after 2

用 sh -x test1.sh 看一下執行過程:

testuser@localhost ~ $ sh -x test1.sh

+ echo 1
1
+ ./test2.sh
2
+ echo after 2
after 2

 

那麼為什麼 Jenkins 的 shell script,

看起來是在 test2.sh 回傳錯誤之後,就整個停下來了呢?

查了一下,原來 Jenkins 是使用類似 sh -xe 的方式來執行,

這邊的 -e 選項就是在 shell script 有執行錯誤時,立刻停止~

 

用 sh -xe 來執行看看,

果真在執行完 test2.sh 回傳非零值之後,

就沒再印出 “after 2” 的訊息了:

testuser@localhost ~ $ sh -xe test1.sh

+ echo 1
1
+ ./test2.sh
2

 

如果想在程式裡覆寫掉這個行為,

可以在 test1.sh 開頭加上 set +e,這樣就不會在執行錯誤時停下來。

另一個作法就是想辦法避免錯誤發生囉~

 

參考資料:

don’t fail jenkins build if execute shell fails

What does set -e mean in a bash script?

 

(本頁面已被瀏覽過 1,698 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料