Making Your zsh Return You to a Non-Production Setting

I have my prompt in zsh setup to display what Kubernetes context I am pointing to, so that I will notice if I’m somehow pointed at production environments, but I’m still wary of being asked to check things in production and then forgetting to point back to a “safe” environment before doing something else.

So I set up a preexec and precmd hook to store state for the session that I’m in. In the preexec, I save off whatever command was run.

In the precmd, I check to see that command matches “switching over to production”, mark the time, and clear the command out (otherwise, pressing <return> on the shell will keep the same command).

If I have marked the time I switched to production (PROD_TIME is not an empty string), then I check the current time and if it’s past a threshold (15 seconds in the current case), then I run the command to switch back.

The last few lines clear the prexec and precmd function hooks and set them to the “safety” functions.

function safety_preexec() {
# Store the command that we're running.
function safety_precmd() {
if [[ "$CMD_NAME" =~ 'kubectl config use-context whatever-your-prod-is' ]]; then
PROD_TIME=$(date +%s)
if ! [[ -z "$PROD_TIME" ]]; then
CURRENT_TIME=$(date +%s)
kubectl config use-context whatever-your-dev-is
[[ -z $preexec_functions ]] && preexec_functions=()
preexec_functions=($preexec_functions safety_preexec)
[[ -z $precmd_functions ]] && precmd_functions=()
precmd_functions=($precmd_functions safety_precmd)

view raw


hosted with ❤ by GitHub

%d bloggers like this: