-3

What according to you is the best way to log errors of a script.

I have tried following ways but nothings seems to complete. ( I have added the exception ) This find command will not work as the user does not have permission to /home/data/work/ directory.

1.)

$(find /home/data/work/. -type f -delete) >log.txt 2>&1

this doesn't write anything to my log.txt

2.)

find /home/data/work/. -type f -delete >log.txt 2>log.txt

here executing command without $() doesn't seems to be correct

3.)

function log_this() {
echo "$(date): $*" | tee -a log.txt
}
$(find /home/data/work/. -type f -delete) || { log_this "error"; exit 1; }

This will log a massage "error" to logfile, but here I can't redirect the error from the command to log_this function.

What are some good ways to generate log of the a script where I can use $() and write a custom message and original error to logfile.

5
  • There is a misconception: command substitution is not a command. Instead of asking for "the best way", please ask for you are really trying to do.
    – sebelk
    Jun 1 '20 at 16:44
  • @sebelk : I have added sample code of what am I doing
    – ETL_Devs
    Jun 2 '20 at 9:06
  • again: command substitution is not the same that a command. You're mistaking that in examples 1) and 3). Read the bash man page.
    – sebelk
    Jun 2 '20 at 12:31
  • there is no mistake in command, its a different approach , i am not sure what you are trying to point out
    – ETL_Devs
    Jun 2 '20 at 12:36
  • 1
    approach of what? again, you have a misconception Please, test this simple example, run in a shell (you're not telling what shell you're using), date and then $(date) you'll see that a command substitution is not the same that a command.
    – sebelk
    Jun 2 '20 at 12:42
0

You seem to be stepping around the correct solution by either

  1. Running the output of find as a command (this is what happens when you use find in a command substitution and then use that command substitution as a command, which you do in option 1 and 3), or
  2. Redirect the output and error streams separately to log.txt.

The correct variation would be

find ... >log.txt 2>&1

That is, run the command and redirect the output to the file, then also redirect the error stream to where the standard output goes.

If you only want to log the errors, then don't redirect standard output:

find ... 2>log.txt

In the moreutils package, you will find a command called ts that you could use to get timestamps in output from commands:

find ... 2>&1 >/dev/null | ts >log.txt

The above command would discard the standard output from find but add timestamps to the error output and store it in log.txt.

0

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.