Tuesday, April 15, 2014

adding a timestamp to bash stdout

Assume a shell script writes without timestamp info:

myscript.sh
bla 
mumble

how long it took to complete bla? and mumble? no clue. You could hack the script to add a timestamp for each echo, but that's not practical. Workaround:

vi timestamp.sh

#! /bin/bash

while read line
do
echo `date +"%Y%m%d-%H%M%S"` $line
done



chmod 775 timestamp.sh

now you can use it this way:

myscript.sh | ./timestamp.sh

20140415-145529 bla
20140415-145529 mumble


In alternative, you can also compile this c program:
//gcc timestamplog.c -o timestamplog

#include 
#include 

time_t now;
struct tm  *ts;
char buf[80];

void printTime() {
    now = time(NULL);
    ts = localtime(&now);
    strftime(buf, sizeof(buf), "%Y%m%d-%H%M%S  ", ts);
    printf("%s", buf);
}


int main() {
 int startLine = 1;
 int ch;
    while ((ch = getchar()) != EOF) {
  if (startLine) {
   printTime();
   startLine = 0;
  }
  
  if (ch == 10 || ch == 13) {
      //putchar('\n');
      putchar(ch);
      startLine = 1;

  } else {
         putchar(ch);
  }
  fflush(stdout);
    }

    return 0;
}




No comments: