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
dev
  • 129
  • 2
  • 7
  • 1
    Have you already seen this answer? It could be useful to fully understand || – Francesco May 22 '20 at 09: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 – dev May 22 '20 at 09:56

1 Answers1

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.

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