How do I use colors in the MOTD?

Assuming you are on Ubuntu - which uses dash to run system scripts:

That file, /etc/update-motd.d/00-header, is executed by /bin/dash, (not /bin/bash,) which is pretty minimalistic (and fast) -
it seems to not support the "\e" in this place - use "\033" instead.

It is different in when to expand escape codes.


On Debian/Ubuntu the motd is configured in /etc/pam.d/sshd:

session    optional     pam_motd.so  motd=/run/motd.dynamic
session    optional     pam_motd.so noupdate

which means that upon successful login the system will run something like:

cat /run/motd.dynamic
if [[ -f /etc/motd ]]; then cat /etc/motd; fi

where /etc/motd is the static part (only printed, not sourced).

Debian 9 / Ubuntu 16.04:

For generating the dynamic part run-parts is used for /etc/update-motd.d directory:

/usr/bin/env -i PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin run-parts --lsbsysinit /etc/update-motd.d

For slightly more readable code you can use tput setaf {color number}. Note that to preserve colors we have to set TERM variable.

#!/bin/sh
export TERM=xterm-256color

read one five fifteen rest < /proc/loadavg
echo "$(tput setaf 2)
Kernel: `uname -v | awk -v OFS=' ' '{print $4, $5}'`
$(tput setaf 4)Load Averages......: ${one}, ${five}, ${fifteen} (1, 5, 15 min)
$(tput setaf 5)
 ______________
< Hello World! >
 --------------
        \\   ^__^
         \\  (oo)\\_______
            (__)\\       )\\\/\\
                ||----w |
                ||     ||

$(tput sgr0)"

save the file as e.g. /etc/update-motd.d/10-uname

and make sure it's executable:

chmod +x /etc/update-motd.d/10-uname

Basic colors are numbered:

  • 1 – Red
  • 2 – Green
  • 3 – Yellow
  • 4 – Blue
  • 5 – Magenta
  • 6 – Cyan
  • 7 – White

The code above generate: bash colored motd

Depending on your taste you can produce more colorful output using lolcat or headings from figlet. Generated output uses standard bash syntax:

^[(B^[[m
^[[32m
Kernel: 4.9.65-3+deb9u2 (2018-01-04)
^[[34mLoad Averages......: 0.04, 0.05, 0.05 (1, 5, 15 min)
^[[35m
 ______________
< Hello World! >
 --------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

^[(B^[[m

Debian 8 / Ubuntu 14.04

The dynamic part is updated using /etc/init.d/motd start that executes following:

uname -snrvm > /var/run/motd.dynamic