Add a function in shell on Linux (make dmesg timestamps human readable)

You want to add a specific function on your shell which is not available in standard functions and you would like to be able to call it anywhere you want without the need to specify the script location? That’s quite easy to do, with some simple tricks 😉 !

We will here work with a simple example of a useful function:

When you are calling the dmesg command, you got a timestamp which is not human readable and it can be hard to align these logs with the logs of another application running on the server for example. We will create a function called dmesghr (for dmesg human readable) that will allow us to call exactly the same than the dmesg command but with a timestamp human readable.

First of all, we will create our function under our profile at the end of file ~/.bashrc after all the already existing declarations:

[...]
# Function translating dmesg timestamp into a timestamp human readable
function dmesghr {
    # Define date format (similar to syslog)
    date_format="%b %d %T %Y"

    # Get the uptime in seconds from /proc/uptime
    uptime=$(cut -d " " -f 1 /proc/uptime)

    # Read dmesg and convert date with date_format defined above
    dmesg | sed "s/^\[[ ]*\?\([0-9.]*\)\] \(.*\)/\\1 \\2/" | while read timestamp message; do
        printf "[%s] %s\n" "$(date --date "now - $uptime seconds + $timestamp seconds" +"${date_format}")" "$message"
    done
}

Once this done, we will reload the profile file and export our new function so we can use it anywhere:

~$source ~/.bashrc
~$export -f dmesghr

Right now, we can call it directly from our shell and use it as a standard function:

~$dmesghr
[...]
[jan. 21 09:34:00 2015] Initializing cgroup subsys cpuset
[jan. 21 09:34:00 2015] Initializing cgroup subsys cpu
[jan. 21 09:34:00 2015] Initializing cgroup subsys cpuacct
[jan. 21 09:34:00 2015] Linux version 3.13.0-39-generic (buildd@toyol) (gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1) ) #66-Ubuntu SMP Tue Oct 28 13:30:27 UTC 2014 (Ubuntu 3.13.0-39.66-generic 3.13.11.8)
[jan. 21 09:34:00 2015] Command line: BOOT_IMAGE=/boot/vmlinuz-3.13.0-39-generic root=UUID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx ro quiet splash vt.handoff=7
[jan. 21 09:34:00 2015] KERNEL supported cpus:
[jan. 21 09:34:00 2015] Intel GenuineIntel
[...]