Itai Ganot
Itai Ganot

Reputation: 6305

How to output both command and output of the command to both console and log?

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?

Upvotes: 0

Views: 221

Answers (1)

Würgspaß
Würgspaß

Reputation: 4820

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

Upvotes: 2

Related Questions