如何将命令和命令输出同时输出到控制台和日志? [英] How to output both command and output of the command to both console and log?

查看:85
本文介绍了如何将命令和命令输出同时输出到控制台和日志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下bash函数:

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.

修改:这就是我在脚本中使用该函数的方式:

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.

怎么办?

推荐答案

我希望在添加时将输出同时发送到控制台和日志日期和时间仅位于日志中命令本身所在的行

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

这篇关于如何将命令和命令输出同时输出到控制台和日志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆