I need to redirect the output of a command that I am running to a log file with timestamp (hence a function instead of the log file itself) but the error and the output, both should not be showing in the console. The following -
command | my_func 2> /dev/null is not working.
Something like
command 2> logfileworks, but I can't record the timestamp in the second case. What should I do?
4 Answers
It seems you want:
command 2> /dev/null | my_func which redirects the stderr of command to /dev/null, but pipes stdout to my_func. (Side note: You might want to check out the ts command).
You do not even need a function for that!
To redirect errors to /dev/null and output to a file with time and date, you could use sed like so:
command 2> /dev/null | sed -e "s/^/$(date) /" >> logfile sed -e "s/^/$(date) /" will append the current date in this format Thu 09 Apr 2020 07:06:14 AM +03 to the beginning of each line and add a space between the date and the output for readability purposes.
Notice:
- To redirect both error and output to a file with time and date, use this:
command 2>&1 | sed -e "s/^/$(date) /" >> logfile- To use timestamp in seconds since the Unix epoch like this
1586406740. change$(date)to$(date +%s)
Best of luck
8If a timestamp is all that is needed see ts from the moreutils package.
command | ts
$ sudo apt install moreutils 1 Another option is to use GNU awk:
myprogram | gawk '{print strftime(), $0}' >> logfileIf you also want to log standard error (assumes bash shell):
myprogram |& gawk '{print strftime(), $0}' >> logfile