What is idempotency?

Idempotent scripts can be called multiple times and each time it’s called, it will have the save effects on the system. This means, a second call will exit with the same result and won’t have any side effects.

Examples

Creating an empty file

touch example.txt

Creating a directory

mkdir -p mydir
ln -sfn source target

Removing a file

rm -f example.txt

Check if variable, file or dir exists

if [ ! -f "/etc/conf/foo.txt" ]; then
  echo "ttt" > /etc/conf/foo.txt
fi

Other flags:

  • -f file
  • -d directory
  • -z string of zero length
  • -p pipe
  • -x file and has execute permission, -x "$(command -v op)" check op binary is or not installed in your machine

Use if for conditional choice

if [ "$Name" != $USER] ...

Use "$Name" rather than $Name. If $Name is empty, bash sees the above condition as

if [ != $USER] ...

Thus add "" is the safe way to use variable in condition.

Reference