Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a conditional newline in PS1?

Tags:

bash

shell

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$ 
like image 666
Ali Avatar asked Feb 13 '13 17:02

Ali


2 Answers

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.
like image 105
dogbane Avatar answered Oct 05 '22 04:10

dogbane


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
  }'
like image 33
chepner Avatar answered Oct 05 '22 03:10

chepner