Search code examples
bashshellps1

How to set a conditional newline in PS1?


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\$ ", so first time (i.e., right after login) you get:

hostname:~ username$ 

I’ve been trying something like in my ~/.bashrc:

function __ps1_newline_login {
  if [[ -n "${PS1_NEWLINE_LOGIN-}" ]]; then
    PS1_NEWLINE_LOGIN=true
  else
    printf '\n'
  fi
}

export PS1="\$(__ps1_newline_login)\h:\W \u\$ “

expecting to get:

# <empty line>
hostname:~ username$ 

A complete example from the the beginning would be:

hostname:~ username$ ls `# notice: no empty line desired above!`
Desktop      Documents

hostname:~ username$ 

Solution

  • 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.