我希望所有對我的shell腳本執行的命令的錯誤的日誌文件中寫的,這是簡單的執行如何在日誌中發送錯誤,在shell腳本中添加日期?
exec 2>> /var/log/mylog.txt
,但如果我想的錯誤之前添加到每一行的日期是什麼?
我希望所有對我的shell腳本執行的命令的錯誤的日誌文件中寫的,這是簡單的執行如何在日誌中發送錯誤,在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
創建管道並通過perl腳本運行stderr。喜歡的東西:
#!/bin/sh
trap 'rm -f $F' 0
F=$(mktemp)
rm $F
mkfifo $F
perl -ne 'print localtime() . ": " . $_' < $F >&2 &
exec 2> $F
書面,這個打印時間戳和消息,以相同的標準錯誤的腳本了的時候纔開始,這樣你就可以在運行腳本時重定向追加到一個日誌文件。或者你可以在調用perl
的行上硬編碼重定向。
想到的第一個選項是使用fifo和一些重定向:
我維護此答案,因爲它可能已足夠;但有其它選擇 - 看到我的其他答案
#!/bin/sh
TEMPDIR=`mktemp -d`
mkfifo "${TEMPDIR}/fifo"
(awk '{"date" | getline the_date; print the_date ": " $0; fflush() }' < "${TEMPDIR}/fifo") &
exec 2> "${TEMPDIR}/fifo"
rm -f "${TEMPDIR}/fifo"
#
# Your commands here
#
exec 2>&-
可能重複[如何將時間戳添加到STDERR重定向](http://stackoverflow.net M /問題/ 1507674 /如何到添加時間戳到標準錯誤重定向) – Arseniy