How to set a conditional newline in PS1?

前端 未结 3 1103
感动是毒
感动是毒 2020-12-31 05:25

I am trying to set PS1 so that it prints out something just right after login, but preceded with a newline later.

Suppose export PS1=\"\\h:\\W \\u

3条回答
  •  时光说笑
    2020-12-31 06:23

    Running with dogbane's answer, you can make PROMPT_COMMAND "self-destruct", preventing the need to run a function after every command.

    In your .bashrc or .bash_profile file, do

    export PS1='\h:\W \u\$ '
    reset_prompt () {
      PS1='\n\h:\W \u\$ '
    }
    PROMPT_COMMAND='(( PROMPT_CTR-- < 0 )) && { 
      unset PROMPT_COMMAND PROMPT_CTR
      reset_prompt
    }'
    

    When the file is processed, PS1 initially does not display a new-line before the prompt. However, PROMPT_CTR is immediately decremented to -1 (it is implicitly 0 before) before the prompt is shown the first time. After the first command, PROMPT_COMMAND clears itself and the counter before resetting the prompt to include the new-line. Subsequently, no PROMPT_COMMAND will execute.

    Of course, there is a happy medium, where instead of PROMPT_COMMAND clearing itself, it just resets to a more ordinary function. Something like

    export PS1='\h:\W \u\$ '
    normal_prompt_cmd () {
       ...
    }
    reset_prompt () {
      PS1='\n\h:\W \u\$ '
    }
    PROMPT_COMMAND='(( PROMPT_CTR-- < 0 )) && {
       PROMPT_COMMAND=normal_prompt_cmd
       reset_prompt
       unset PROMPT_CTR
      }'
    

提交回复
热议问题