Skip to content

Instantly share code, notes, and snippets.

@dergachev
Last active September 28, 2016 14:56
Show Gist options
  • Save dergachev/5766167 to your computer and use it in GitHub Desktop.
Save dergachev/5766167 to your computer and use it in GitHub Desktop.
shell snippet to prepend timestamp to command output

prepend-timestamp

Shell snippet that prepends a nice to a command's output.

For example, here's the (snipped) output of VAGRANT_LOG=debug vagrant provision:

INFO environment: Home path: /Users/dergachev/.vagrant.d
WARN environment: No local data path is set. Local data cannot be stored.
WARN environment: In a bundler environment, not loading environment plugins!
INFO environment: Running hook: environment_load
INFO environment: Initializing config...

Would you prefer to see the following?

17:47:19:938 INFO environment: Home path: /Users/dergachev/.vagrant.d
17:47:19:939 WARN environment: No local data path is set. Local data cannot be stored.
17:47:19:939 WARN environment: In a bundler environment, not loading environment plugins!
17:47:19:939 INFO environment: Running hook: environment_load
17:47:19:948 INFO environment: Initializing config...

Then simply modify the above command as follows:

vagrant provision 2>&1 | ruby -ne 'puts "\e[33m" + Time.now().strftime("%T.%L") + "\e[0m " + $_'

Keep in mind the following:

  • 2>&1 redirects stderr to stdout (pipes only work on stdout)
  • \e[33m and \e[0m are terminal escape codes that make the text between them yellow
  • %T is HH:MM:SS and %L adds milliseconds in the time formatting command.

Installing the script

Prefer to invoke the script in a friendlier way?

vagrant up 2>&1 | prepend-timestamp

Then do the following:

## 
## Creates a ~/bin folder and ensure it's in $PATH; 
## via http://askubuntu.com/a/247422/194314
##
mkdir ~/bin
cat - >> ~/.bashrc <<'EOT'
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi
EOT
source ~/.bashrc

##
## Installs ~/bin/prepend-timestamp and makes it executable
##
cat - > ~/bin/prepend-timestamp <<'EOT'
#!/bin/sh
ruby -ne 'puts "\e[33m" + Time.now().strftime("%T.%L") + "\e[0m " + $_'
EOT

chmod u+x ~/bin/prepend-timestamp

Done!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment