Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Append command output and timestamp to file

Tags:

bash

shell

Normally in my bash scripts I'm used to do some_command >> log.log. This works fine, however how can I append more data like time and command name?

My goal is to have a log like this

2012-01-01 00:00:01 [some_command] => some command output...
2012-01-01 00:01:01 [other_command] => other command output...

The processes should running and writing to the file concurrently.

The final solution, pointed by William Pursell in my case would be:

some_command 2>&1 | perl -ne '$|=1; print localtime . ": [somme_command] $_"' >> /log.log &

I also added 2>&1 to redirect the STDOUTand STDERR to the file and an & on the end to keep the program on background.

Thank you!

like image 888
TCB13 Avatar asked Oct 20 '25 04:10

TCB13


2 Answers

Given your comments, it seems that you want multiple processes to be writing to the file concurrently, and have a timestamp on each individual line. Something like this might suffice:

some_cmd | perl -ne '$|=1; print localtime . ": [some_cmd] $_"' >> logfile

If you want to massage the format of the date, use POSIX::strftime

some_cmd | perl -MPOSIX -ne 'BEGIN{ $|=1 }
   print strftime( "%Y-%m-%d %H:%M:%S", localtime ) . " [some_cmd] $_"' >> logfile
like image 128
William Pursell Avatar answered Oct 22 '25 20:10

William Pursell


An alternative solution using sed would be:

some_command 2>&1 | sed "s/^/`date '+%Y-%m-%d %H:%M:%S'`: [some_command] /" >> log.log &

It works by replacing the beginning of line "character" (^). Might come in handy if you don't want to depend on Perl.

like image 27
estan Avatar answered Oct 22 '25 21:10

estan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!