linux - 如何在日志中发送错误,在 shell 脚本中添加日期?

标签 linux shell logging sh

我希望在我的 shell 脚本中执行的命令的所有错误都写在一个日志文件中,这很容易执行

exec 2>> /var/log/mylog.txt

但是如果我想在每一行中添加错误前的日期怎么办?

最佳答案

如果您正在使用 bash,您可以访问可能用于此目的的协同处理:

#!/bin/bash

# The co-process responsible to add the date
coproc myproc {
       ( bash -c 'while read line; do echo $(date): ${line}; done' 3>&1 1>&2- 2>&3- )
}

# Redirect stderr to the co-process
exec 2>&${myproc[1]}

# Here my script -- classical; no (visible) redirection
ls non-existant-file1 existant-file non-existant-file2

将上面的内容保存为t.sh:

sh$ touch existant-file
sh$ ./t.sh 2> error.log
existant-file
sh$ cat error.log
Tue Jul 15 00:15:29 CEST 2014: ls: cannot access non-existant-file1: No such file or directory
Tue Jul 15 00:15:29 CEST 2014: ls: cannot access non-existant-file2: No such file or directory

关于linux - 如何在日志中发送错误,在 shell 脚本中添加日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24737415/

相关文章:

c++ - 请求 URL 并在 c++ 中在后台运行

spring-boot - Spring Boot 一次为所有测试设置日志级别(无需更改每个测试)

hadoop - 找不到Hadoop日志文件

php - 拉维尔 5.1 : sendOutputTo() truncating log file?

linux - Cassandra备份目录占用2GB

linux - nwjs 如何在 linux 上分发应用程序?

linux - 如何通过比较文件名和文件夹名将文件复制到同名文件夹?

linux - 如何告诉 CMake 将构建文件放在哪里?

c - 与其他 Linux 发行版相比,fork() 在 Ubuntu 上的工作方式是否不同?

Linux 定义自定义 Shell 命令?