In zsh, there exists Hook Functions
, and one of these Hook Functions
is the preexec
function.
The preexec
function is executed just after a command has been read and before it has been executed.
In zsh, we can define a custom prexec
function in the .zshrc
configuration.
I will show how I utilized the prexec
function to prompt for extra confirmation before running certain commands. This custom function will help me to think twice before running critical commands, for instance, commands targeting a production Kubernetes cluster.
In .zshrc
,
# Hooks
pre_validation() {
# Get the current command
local current_cmd=$(echo $1 | xargs)
# Match the command against regexes
if [[ "$current_cmd" =~ ^"rm -rf" ]] || \
[[ "$current_cmd" =~ ^"git reset --hard HEAD" ]] || \
[[ "$current_cmd" =~ ^"git add ." ]] || \
[[ "$current_cmd" =~ .*"prod".* ]]; then
echo "THIS COMMAND MATCHED THE DANGER FILTER! PLEASE CONFIRM THAT THE COMMAND SHOULD RUN."
echo "[ANY] = confirm [Ctrl+c] = decline"
read -sk key
fi
}
The function is simple,
- Read the input command
- Match the command against regexes
- If the command matches any of the regexes
- Show a warning text
- Wait for user input by
read -sk key
which gives the user the possibility to send theSIGINT
signal byCtrl + c
, hence terminating the process
To activate the custom preexec
function, add these two lines the .zshrc
and then run source ~/.zshrc
autoload -U add-zsh-hook # Load the zsh hook module
add-zsh-hook preexec pre_validation # Adds the pre-hook
To deactivate the custom preexec
function we need to add the following line
add-zsh-hook -d preexec pre_validation
Examples
Hopefully, this will help me to overcome the bad habit of running git add .