Search code examples
zshoh-my-zsh

ZSH - print java version in right prompt


I have a daily use case where I need to work with projects on different version of Java (8, 11, ...).

I would like to have it displayed in the right side prompt in my shell (ZSH with Oh-My-Zsh). I know of a dummy way (computationally expensive) to do it (just java --version to var and display it). I would like it to have it cached until I don't source a file (which is a specific project file that sets the new env vars for different java versions).

Do you have any ideas how to do this efficiently?

Br, Stjepan


Solution

  • The PROMPT and RPROMPT variables can have both static and dynamic parts, so you can set the version there when you source the project file, and it will only be calculated one time. The trick is to get the quoting right.

    This line goes in the project file that sets the env variables, somewhere after setting PATH to include the preferred java executable:

    RPROMPT="${${=$(java --version)}[1,3]}"
    

    The pieces:

    • RPROMPT= - variable for the right-side prompt.
    • "..." - the critical part. Variables in double quotes will be expanded then and there, so the commands within this will only be executed when the project file is sourced.
    • ${...[1,3]} - selects the first three words of the enclosed expression. On my system, java --version returns three lines of data, which is way too big for a prompt; this reduces it to something manageable.
    • ${=...} - splits the enclosed value into words.
    • $(java --version) - jre version info.