0

I want to set my PS1 prompt to the output from a function, but when I try to include ansi color sequences, bash will think the line length is longer than it actually is and mess up when you type enough after it to go to a new line. Here's what the code looks like:

ps1() {
    echo -ne "\033[01;34m$(dirs -0)\033[0m \$ "
}
PS1='$(ps1)'
Jake
  • 2,106
  • 1
  • 24
  • 23

1 Answers1

1

Put \[ and \] around escape sequences. This tells the shell not to count them when determining the width of the prompt.

ps1() {
    echo -ne "\\[\033[01;34m\\]$(dirs -0)\\[\033[0m\\] \$ "
}

See Bash Prompt Escape Sequences for all the special sequences you can use in the prompt (e.g. you can use \e instead of \033 for Escape, and \w for the current directory instead of $(dirs -0)).

You need to double the backslashes in these sequences to keep them from being eaten by echo -e. But if you just use the escape sequences listed at the above page, you don't really need -e, since bash will process the escape sequences in PS1 itself.

Barmar
  • 741,623
  • 53
  • 500
  • 612