bashwindows-subsystem-for-linuxoh-my-posh

oh-my-posh on bash, how can I display the current command history number


In bash, I can set my command prompt to be the current history number (PS1=\!). How can I do this with oh-my-posh? I know how to get the current prompt counter with {{ .PromptCount }}, but not the current history number.


Solution

  • To solve this problem, you need to override the set_poshcontext function. I put it at the end of my .bashrc as follows.

        eval "$(oh-my-posh init bash --config ~/history.omp.json)"
        function set_poshcontext() {
          export CURRENT_HISTORY_NUMBER=$(history -n ~/.bash_history; awk '{print $1}' < <(history 1))
        }
        export -f set_poshcontext
    

    Make sure that the set_poshcontext() function is exported after the oh-my-posh init. Every time the prompt is formed, CURRENT_HISTORY_NUMBER is updated. It can then be used in the oh-my-posh config file as follows.

        {
          "type": "text",
          ...
          "template": "{{ .Env.CURRENT_HISTORY_NUMBER }}"
        }
    

    Thanks to @diego for the bash code, which is used verbatim.