Search code examples
command-promptzsh

zsh: Add a warning to the prompt is a specific condition is met


My case

I am working on a remote machine which accesses AWS. I have 3 .aws/credential files:

credentials
dev-credentials
root-credentials

When I want to use my root credentials, I use the following .zshrc aliases:

alias rootcert="cp ~/.aws/root-credentials ~/.aws/credentials"
alias devcert="cp  ~/.aws/dev-credentials  ~/.aws/credentials"

My problem

Using root certificates is dangerous, and I would like a strong visual command prompt indication that I'm using it. The condition to test that is simple - whether the content of ~/.aws/root-credentials equals the one of ~/.aws/credentials.

My question

How can I add a (bold red!) text to my prompt whenever two files are identical?


Solution

  • A better approach to managing the cert files may be using symlinks. Let me construct a setup very similar to yours that you can adapt. You can just enter all of these right into your Zsh session.

    cd tmp
    touch creds-dev creds-root
    ln -s creds-root creds-active
    

    These are named with a consistent creds prefix to show up together in a listing.

    Now you have a symlink that you can change at-will to point to one or the other. E.g., to make the dev version active:

    ln -sf creds-dev creds-active
    

    A function that can check which is active uses readlink to follow the symlink, and looks like:

    certdetect() { [[ $(readlink creds-active) == "creds-root" ]] &&
        print -P '%K{red}%BROOTCERT%b%k ' || print }
    

    The -P tells print to process prompt characters. The %K is for setting background; %B is bold. The %b and %k turn them back off. The net results is a bold red ROOTCERT. This is testable now; just try calling it.

    A Zsh prompt calls a precmd function before each rendering. Use it to add your call to certdetect and set a variable based on it:

    precmd() { PR_ROOTCERT=$(certdetect) }
    

    Then you can set your prompt to include the dynamic variable. An example prompt that features only that:

    PROMPT='$PR_ROOTCERT%# '
    

    Once you have all this working, you'll want to add its pieces to your active prompt_«whatever» file.