Time based command aliases in Bash

So this evening I ran “rm *” in the wrong directory, not too bad as my backup was a month old and there’s only a few little changes.

After ensuring I’m now getting a nightly backup I decided that I should really have an interactive rm command at night when I can make mistakes.

The first problem is I need some way for this to run regularly, I discovered that PROMPT_COMMAND is called every time the command prompt is displayed, this however means that the first command run after the late time will set the alias but I think I can live with this.

If it’s after 10pm and before 7am I want rm to be interactive.

Armed with this I set about with the command and came up with:

h=`date +%H`
if [ $h -lt 7 -o $h -gt 22 ]; then 
    alias rm='rm -i'
else 
    ( alias rm 2>/dev/null > /dev/null ) && unalias rm
fi

This needs to be on one line and enclosed in quotes so this lead to:

PROMPT_COMMAND="h=\`date +%H\`; if [ \$h -lt 7 -o \$h -gt 22 ]; then alias rm='rm -i'; else ( alias rm 2>/dev/null > /dev/null ) && unalias rm; fi"

This is on my gentoo machine so I edited the global /etc/bash/bashrc file, not the nicest solution but meh!

PROMPT_COMMAND is already set to do the terminal title based on my TERM setting so I’m altering it after it’s set with:

PROMPT_COMMAND="${PROMPT_COMMAND:-true};h=`date +%H`; if [ \$h -lt 7 -o \$h -gt 22 ]; then alias rm='rm -i'; else [ alias rm > /dev/null ] && unalias rm; fi"

Log out and back in, and checking aliases I’ve got:

alias rm=‘rm -i’

Now I just need to make sure I don’t start hitting Y without checking.

For those wondering why I’m using “${PROMPT_COMMAND:-true}”, when logging into the real console $PROMPT_COMMAND isn’t set resulting in errors displayed each time this is run. Setting a default, if not set, value to true means the command true is run first.