What are idempotent scripts?
- Published at
- Updated at
- Reading time
- 1min
Even though I studied computer science, some terms and concepts won't stick in my head. I have to look up "idempotence" or "idempotent scripts" repeatedly.
Wikipedia defines the term "Idempotence" as follows:
Idempotence 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.
The concept is not hard to understand, though. A script is idempotent when its repeated execution always leads to the same result. Whether it's the first or thirtieth run, it should "just work". This approach seems logical, but not every script follows it.
Consider a script that creates configuration files and directories:
- Does the script still work when it runs a second time, or does it fail because specific files exist already?
- Is the script appending the same lines of code to config files, or does it check if these lines are already included?
- Are there other side effects that could influence the result of the script?
Fatih Arslan's post How to write idempotent Bash scripts is an excellent explainer on the topic, and it includes many Bash examples on how to reach idempotence. 👏
Join 5.5k readers and learn something new every week with Web Weekly.