Interview Scripting (Bash, Groovy)

What is idempotency, and how do you make a script safe to run repeatedly? [Advanced]

Answer

Idempotency means a script can be run repeatedly and converge to the same desired state without causing duplicate or destructive side effects. I make scripts idempotent by checking current state before changing it and using declarative or upsert-style operations.

Technical explanation

Idempotency is essential for retries, CI/CD, cron jobs, and incident recovery because commands may run more than once.

Use mkdir -p, install -m, kubectl apply, create-if-missing logic, and atomic file replacement.

Avoid blind append, duplicate creates, and repeated destructive actions without guards.

Hands-on example

ensure_user() {

local user="$1"

if id "$user" >/dev/null 2>&1; then

echo "user exists: $user"

else

useradd --system --no-create-home "$user"

fi

}

ensure_user appsvc

mkdir -p /opt/app/releases

Preparing for an interview?

Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.

More Scripting (Bash, Groovy) interview questions

← All Scripting (Bash, Groovy) questions