Skip to content

Instantly share code, notes, and snippets.

@duckythescientist
Last active October 11, 2023 04:13
Show Gist options
  • Save duckythescientist/8338f028e018fd3fecae58e4f1c45def to your computer and use it in GitHub Desktop.
Save duckythescientist/8338f028e018fd3fecae58e4f1c45def to your computer and use it in GitHub Desktop.
Rainbow colored bash prompt PS1 string
# https://stackoverflow.com/a/52465819
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'
}
lololps1() {
# Make a RAINBOW COLORED bash prompt
# Requires lolcat and python
# Implement my version of \w because I can't just outright expand a PS1 string
# Actually, bash 4.4 can do it.... I'm not running 4.4
# Bash argument modification is crazy
# Replace $HOME with ~
mypwd=${PWD/#$HOME/"~"}
# Greedy delete everything before the last forward slash
#mypwd=${mypwd##*/}
# Get the current python virtualenv
myvenv=$(python -c 'import sys;sys.stdout.write(sys.prefix.split("/")[-1] if hasattr(sys, "real_prefix") or hasattr(sys, "base_prefix") and sys.prefix != sys.base_prefix else "")')
# surround with square braces if non-empty
myvenv="${myvenv:+[$myvenv]}"
# Make a persistent, incrementing seed to make a smooth rainbow effect from line to line
if [ -z ${LOLCAT_SEED+x} ]; then LOLCAT_SEED=1; else let "LOLCAT_SEED += 1"; fi
PS1="$myvenv$(whoami)@$HOSTNAME:$mypwd"
PS1="${PS1/duck/🦆}"
PS1="${PS1/duck-kudu/🦌}" # deer
PS1="${PS1/duck-k2/🦕}" # sauropod
# Colorize it
# lolcat -f forces escape sequences even when lolcat doesn't think they'd matter
# lolcat -F changes the frequency of the rainbow
PS1=$(echo "$PS1" | lolcat -f -F 0.7 -S $LOLCAT_SEED 2>/dev/null)
# Strip the "reset colors to normal" commands
PS1=$(echo "$PS1" | sed $'s/\033\[0m//g')
# Replace escape sequences with [escaped escape sequences]
PS1=$(echo "$PS1" | readline_ANSI_escape)
# change the color back to white and add the $/# PS1 character
PS1="${PS1}\[\033[0m\]\$ "
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment