How to set a conditional newline in PS1?

前端 未结 3 1124
感动是毒
感动是毒 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:05

    Try the following:

    function __ps1_newline_login {
      if [[ -z "${PS1_NEWLINE_LOGIN}" ]]; then
        PS1_NEWLINE_LOGIN=true
      else
        printf '\n'
      fi
    }
    
    PROMPT_COMMAND='__ps1_newline_login'
    export PS1="\h:\W \u\$ "
    

    Explanation:

    • PROMPT_COMMAND is a special bash variable which is executed every time before the prompt is set.
    • You need to use the -z flag to check if the length of a string is 0.

提交回复
热议问题