2023-09-30 Confirming potentially dangerous actions

A common situation is when I want to do something on my computer with possibly destructive consequences, like deleting a file, truncating a database table etc. One common approach to making sure this won’t happen accidentally is to require the user to press y or even type yes (this is what Emacs does with its y-or-n-p and yes-or-no-p functions). Some time ago I had a similar need in a shell script. I was afraid, however, that even requiring the user to type yes is not enough – it is easy to condition oneself to type a three-letter word without much thinking, after all.

So, I came up with an idea of telling the user to type a different word every time. More precisely, selecting the word to type at random from some large list, which theoretically may result into the same one twice, but it’s very improbable. (Interestingly, another person had almost the same idea very recently, too.)

And here is the code that accomplishes exactly that. You can put it in the beginning of a script doing some dangerous thing, or wrap it in a Bash function and call it only in the appropriate place, etc.

WORD=$(grep -E '^[a-z]{4,5}$' /usr/share/dict/words | shuf -n1)
read -rp "Type the word '$WORD' if you really want to turn the friction contrafibulator on: " TYPED
if [ "$WORD" != "$TYPED" ]; then
        echo You typed \'"$WORD"\' wrong, aborting.
        exit 1
fi

I decided to only go with 4 or 5 letter words, so that I don’t have to type anything too short nor too long. Of course, this creates a small risk of getting, well, certain 4-letter words, but let’s not overthink that. On my machine, grep -E '^[a-z]{4,5}$' /usr/share/dict/words | wc -l reports well over 7000 results, which is more than enough for my purpose.

I installed this code in one of the scripts I’ve written which must not be run accidentally (but which I need to run from time to time), and so I’ll see how it works – so far, it seems to do its job.

CategoryEnglish, CategoryBlog