Change Your Linux PS1 Prompt to Use Color

In Linux you can change your PS1 variable to be more colorful, have additional info available, and even run commands.

Bash PS1 basic prompt
Bash PS1 basic prompt


\u – User
@
\h – Hostname
\w – Working Dir
$

export PS1="\[email protected]\h \w $ "

You can do lots of neat tricks with the power of running commands on your prompt. These commands will run each time you run a command, so they should have low resource usage and able to complete in less than a second.

Here is an example using the built-in $SECONDS variable and running it through awk so we can see how long our current bash session has been open.

Bash PS1 advanced prompt
Bash PS1 advanced prompt


D{%m} – Month
/
D{%d} – Day
D{%T} – 24-hour HH:MM:SS
\h – Hostname
echo \$SECONDS – Seconds of current bash session
awk… – Print out m h d w M for longer run timess
\w – Working Dir
$

color(){
tput setaf $1
}

export PS1="\[$(tput bold)\]\[$(color 2)\]\D{%m}\
\[$(color 45)\]/\
\[$(color 2)\]\D{%d} \
\[$(color 45)\]\D{%T} \
\[$(color 2)\]\h \
\[$(color 45)\]\$(echo \$SECONDS | awk '\
\$1 < 60 {print \$1\"s\"} \
\$1 >= 60 && \$1 < 3600 {printf \"%0.1fm\",\$1/60} \
\$1 >= 3600 && \$1 < 86400 {printf \"%0.1fh\", \$1/60/60} \
\$1 >= 86400 && \$1 < 604800 {printf \"%0.1fd\", \$1/60/60/24} \
\$1 >= 604800 && \$1 < 2629746 {printf \"%0.1fw\", \$1/7/24/60/60} \
\$1 >= 2629746 {printf \"%0.1fM\", \$1/30.436875/60/60/24}') \
\[$(color 7)\]\w \
\[$(color 2)\]\$ \
\[$(color 7)\]"