Question: In a Bash Prompt (PS1 variable), I'm calling a function to potentially add text to the prompt: `export PS1="\u@\h \$(my_function) \$ "`

However, the function in the prompt contains ANSI color codes that change based on the output of the function (sometimes red, sometimes green). Adding "`\[`" to the PS1 variable should escape those codes as non-printing, but if I do an `echo` in the function, the "`\[`" get printed literally in the prompt.

How can I escape these ANSI color codes from within a function for use in a bash prompt?

Answer: 
Based on [grawity's answer](https://superuser.com/a/301355/365890), the following will enclose ANSI control sequences in ASCII `SOH` (`^A`) and `STX` (`^B`) which are equivalent to `\[` and `\]` respectively:

```
function readline_ANSI_escape() {
  if [[ $# -ge 1 ]]; then
    echo "$*"
  else
    cat  # Read string from STDIN
  fi | \
  perl -pe 's/(?:(?<!\x1)|(?<!\\\[))(\x1b\[[0-9;]*[mG])(?!\x2|\\\])/\x1\1\x2/g'
}

```

Use it like:

```
$ echo $'\e[0;1;31mRED' | readline_ANSI_escape

```

Or:

```
$ readline_ANSI_escape "$string"

```

As a bonus, running the function multiple times will not re-escape already escaped control codes.
If you want to use them in the prompt, then you do need to do the `\[`. But if you want to use it in an echo, you have to use `\033[`.