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 provision:

Successfully installed bundler-1.3.5  
1 gem installed  
Using rmagick (2.13.2)  
Using bundler (1.3.5)  
Use `bundle show [gemname]` to see where a bundled gem is installed.  
[default] Running provisioner: shell...  
[default] Running: inline script  

Would you prefer to see the following?

18:32:05.055   Successfully installed bundler-1.3.5  
18:32:05.055   1 gem installed  
18:32:05.282   Using rmagick (2.13.2)  
18:32:05.282   Using bundler (1.3.5)  
18:32:05.285   Use `bundle show [gemname]` to see where a bundled gem is installed.  
18:32:05.291   [default] Running provisioner: shell...  
18:32:05.789   [default] Running: inline script  

Then simply append this snippet to your 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