How to set conditional new line in PS1?

I'm trying to set it PS1so that it prints something right after logging in, but later a new line was added to it.

Suppose export PS1="\h:\W \u\$ ", therefore, for the first time (i.e. immediately after entering the system) you will receive:

hostname:~ username$ 

I am trying something like mine ~/.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 receive:

# <empty line>
hostname:~ username$ 

Full example from the beginning:

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

hostname:~ username$ 
+14
source share
3 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 that is executed every time before setting the prompt.
  • You need to use a flag -zto check if the string length is 0.
+13
source

dogbane, PROMPT_COMMAND "", .

.bashrc .bash_profile

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

, PS1 . , PROMPT_CTR -1 ( 0 ), . PROMPT_COMMAND , . PROMPT_COMMAND.

, , PROMPT_COMMAND . -

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
  }'
+5

2018 ( chepner)

:

  • PS1
  • I used "\ n $ PS1" instead of reprinting ( "$var"puts varon a line, only works with double quotes).

Enter the following into ~ / .bash_profile (substituting the first line with the prompt):

PS1=YOUR PROMPT HERE (without newline)

reset_prompt () {
  PS1="\n$PS1"
}
PROMPT_COMMAND='(( PROMPT_CTR-- < 0 )) && {
  unset PROMPT_COMMAND PROMPT_CTR
  reset_prompt
}'
+1
source

All Articles