Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

bash - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...