Ubuntu – How to redirect the output of a command to a function but suppress the error and output to console

basherror handlingstdouttimestamp

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> logfile

works, but I can't record the timestamp in the second case. What should I do?

Best Answer

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

Related Question