Reputation: 83
I have deployed a post-receive hook script and I want to get whole output logs in a file as a block starting with date. I have tried one method but it take line by line log, meaning I have to put that command against every line to get the log. Is there any way to get the whole script log once starting with date?
Script file looks like this:
#!/bin/bash
any_command | ts '[%F %T]' >> /home/Man/Man_log.log
second_command | ts '[%F %T]' >> /home/Man/Man_log.log
third_command | ts '[%F %T]' >> /home/Man/Man_log.log
see i have to put this line | ts '[%F %T]' >> /home/Man/Man_log.log
against every command to get log. And I have 90 lines, so it is not a perfect way to do this. I need an efficient way, like only one line in my script which takes the output of the whole script as log and stores it to another Man_log.log file starting with the date.
What i want is similar to this.
#!/bin/bash
ts '[%F %T]' >> /home/Man/Man_log.log #a command which can store logs of every command below this to a separate file starting with date
any_command
second_command
third_command
Upvotes: 0
Views: 513
Reputation: 26925
Probably the easiest way would be to modify your script to print the date everytime is called:
#!/bin/sh
date -u +"%Y-%m-%dT%H:%M:%SZ"
# your commands below
...
if you can't modify the script then you could group your commands for example:
(date && anycommand) >> out.log
Grouping a (list of commands) in parenthesis causes them to be executed as if they were a single unit. "sub-shell"
Upvotes: 1
Reputation: 477
Let's say this is the script that should give us some logs:
#!/bin/bash
echo "log_line1
log_line2
log_line3
log_line4"
And let's call it script.sh
.
Running it as ./script.sh | printf "%(%F)T {\n$(cat)\n}" >> Man_log.log
, content of Man_log.log
will be:
2018-05-04 {
log_line1
log_line2
log_line3
log_line4
}
Let me now explain what exactly the pipe does.
%(%F)T
is replaced with current date in YEAR-MONTH-DAY format$(cat)
are the logs that are output of ./script.sh
. In general it is data received as standard input.
Basically ./script.sh
writes it's logs to standard output. The pipe then passes that standard output to standard input of echo
. Running cat
without parameters is the same as cat /dev/stdin
.Upvotes: 0