Skip to content

Latest commit

 

History

History
44 lines (29 loc) · 1.56 KB

escape-ansi-sequences.md

File metadata and controls

44 lines (29 loc) · 1.56 KB

Escape ANSI Sequences in Bash

So after writing all about my fancy new shell prompt, I had to adjust it a little. I knew I'd gotten it wrong when I started seeing my shell commands wrap before they reached the end of the window.

A few Google searches found me, as always, in a Stack Overflow article: "Terminal Prompt Not Wrapping Correctly", which had the solution enclosed.

Escape your ANSI Escape Codes!

Apparantely, despite being called ANSI "Escape" Codes, you still need to escape these babies or weird things will happen.

My Original Shell Prompt

Here's what I originally had for my shell prompt.

PS1="\033[0;31m$ \e[0m"

Correctly Escaping the Color Codes

Here's the "proper", correctly escaped prompt. Notice I also escaped the dollar sign!

PS1="\[\033[0;31m\]\$ \[\e[0m\]"

Fancier Colors

I decided to add the CWD, or Current Working Directory, back in to my prompt. Context is key! While I was at it, I moved the color codes into variables so the prompt can be more easily read. Here's the result.

PURPLE="\033[0;31m"
RED="\033[0;35m"
DIR="\W"
COLOR_RESET="\[\e[m"
PS1="\[$PURPLE\]$DIR\[$COLOR_RESET\]\[$RED\]\$\[$COLOR_RESET\] "

Notice the begin and ending escape characters \[ and \] around each color variable.