3

I want to capture and write my error to log file along with custom message.

Consider the command :

$(find $val -type f -delete) || echo "error in deleting files" |tee -a log.txt

This command writes below line in log.txt file

error in deleting files

But I also want to print the error of find command to log filealong with my custom message , so that log file can look like this:

find: `/home/temp': No such file or directory
error in deleting files
2
  • 1
    Have you already seen this answer? It could be useful to fully understand || May 22, 2020 at 9:47
  • yes , I checked that answer , but I can't get around passing stderr to alternate command using || command. it never prints it to file. it just prints it to console , I can use >&2 to pass it to file , but I wanted to pass it to tee command for a unified structure of a big shell script
    – ETL_Devs
    May 22, 2020 at 9:56

1 Answer 1

4

You need to alter the operators precedence there, and group the find || echo commands in a compound command redirected to the pipe to tee:

{ $(find $val -type f -delete) || echo "error in deleting files"; } 2>&1 |tee -a log.txt

or also:

($(find $val -type f -delete) || echo "error in deleting files") 2>&1 |tee -a log.txt

the 2>&1 redirection serves to redirect find's error messages to the pipe read by tee, while echo's output already goes naturally into that pipe.

1
  • oh , I was trying to redirect 2>&1 and then print the stdout to log with message , but this is more better, thanks
    – ETL_Devs
    May 22, 2020 at 11:01

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.