Idempotent Bash Script

看到「How to write idempotent Bash scripts」這篇,重點在講 Idempotence,這個詞是從數學上借來的,講重複操作的不動性:

An element x of a magma (M, •) is said to be idempotent if:

x • x = x.

If all elements are idempotent with respect to •, then • is called idempotent. The formula ∀x, x • x = x is called the idempotency law for •.

在 CS 領域也是一樣的概念:

Idempotence (UK: /ˌɪdɛmˈpoʊtəns/, US: /ˌaɪdəm-/) is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application.

而這篇講的是 Bash 上有些常見的行為要怎麼改成 Idempotence:

It happens a lot, you write a bash script and half way it exits due an error. You fix the error in your system and run the script again. But half of the steps in your scripts fail immediately because they were already applied to your system. To build resilient systems you need to write software that is idempotent.

一個常見的例子是 cron job 是否可以重複執行的問題。

如果 cron job 裡的程式都是 idempotent,那麼就不需要擔心重跑會因為前一隻 script 產生的環境而失敗,導致無限循環而需要人介入...

另外一個更進階的是同時有兩個 process 在執行同一個 script (可能在不同機器上),這也是要考慮的問題,不過這個問題在大多數情況下有各種 lock 系統可以協助避免,應該不是太大的問題...

Leave a Reply

Your email address will not be published. Required fields are marked *