0

I wrote the following bash function:

function log {
    echo "[$(date -u +'%Y-%m-%dT%H:%M:%S.000')]: $*" | tee -ai  $logfile
}

Intending that the output of the commands will be printed to both the console and the log.

Edit: This is how I'm using the function in the script:

log ls -l

In reality, the log contains the commands and not their output, while I want the output to go both to the console and the log while adding the date and time only to the line of the command itself in the log.

How can it be done?

3
  • 1
    So what is not working? Commented Dec 13, 2017 at 10:12
  • I think you did not provide the complete content of your log funcition Commented Dec 13, 2017 at 10:14
  • In the log, I see only the command itself but not the output and no output is going in terminal. Commented Dec 13, 2017 at 10:38

1 Answer 1

2

I want the output to go both to the console and the log while adding the date and time only to the line of the command itself in the log

I think you ask for some function which executes and logs commands. It could look like this:

function executeAndLog {
    echo "[$(date -u +'%Y-%m-%dT%H:%M:%S.000')]: $@" | tee -ai  logfile.txt
    "$@" | tee -ai  logfile.txt
}

executeAndLog ls logfile.txt

which outputs this both to log and console

[2017-12-13T10:38:40.000]: ls logfile.txt
logfile.txt
Sign up to request clarification or add additional context in comments.

1 Comment

Using "$*" instead of "$@" is wrong unless you specifically want to lose quoting. The added call is also a useless use of echo -- you can simply "$@" | tee -ai logfile.txt (sic)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.