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

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?

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).

2

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

8

If 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}' >> logfile

If you also want to log standard error (assumes bash shell):

myprogram |& gawk '{print strftime(), $0}' >> logfile

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like