abi*_*tha 85 bash shell logging redirect
在Unix shell中,我有一个env文件(env文件定义运行用户脚本所需的参数,如日志文件名和路径,重定向输出和错误到日志文件,数据库连接详细信息等),它重定向所有输出(回显消息))使用以下代码从执行的脚本到日志文件的错误:
exec 1>>${LOG_FILE}
exec 2>>${LOG_FILE}
Run Code Online (Sandbox Code Playgroud)
env文件在每个脚本的开头执行.由于env文件中的上述代码,所有可能是用户输出或错误的控制台输出都直接输出到日志文件,这是我实际需要的.
但是我想在控制台和日志文件中显示一些选择性用户输出.但由于上述代码,我无法这样做.
我知道如果我删除上面的代码,我可以得到这种情况下所需的结果,但我必须手动将所有其他输出写入日志文件,这不是一件容易的事.
有没有办法在控制台和日志文件中获取输出而不删除上述代码?
Ian*_*rts 97
exec 3>&1 1>>${LOG_FILE} 2>&1
Run Code Online (Sandbox Code Playgroud)
将stdout和stderr输出发送到日志文件中,但也会让fd 3连接到控制台,所以你可以做
echo "Some console message" 1>&3
Run Code Online (Sandbox Code Playgroud)
只是向控制台写一条消息,或者
echo "Some console and log file message" | tee /dev/fd/3
Run Code Online (Sandbox Code Playgroud)
写一个消息都控制台和日志文件- tee将其输出发送到它自己的FD两个1(这里是LOG_FILE),你告诉它写(在这里是FD 3,即控制台)的文件.
例:
exec 3>&1 1>>${LOG_FILE} 2>&1
echo "This is stdout"
echo "This is stderr" 1>&2
echo "This is the console (fd 3)" 1>&3
echo "This is both the log and the console" | tee /dev/fd/3
Run Code Online (Sandbox Code Playgroud)
会打印
This is the console (fd 3)
This is both the log and the console
Run Code Online (Sandbox Code Playgroud)
在控制台上放
This is stdout
This is stderr
This is both the log and the console
Run Code Online (Sandbox Code Playgroud)
进入日志文件.
Jon*_*rns 37
是的,你想使用tee:
tee - 从标准输入读取并写入标准输出和文件
只需将命令传递给tee并将文件作为参数传递,如下所示:
exec 1 | tee ${LOG_FILE}
exec 2 | tee ${LOG_FILE}
Run Code Online (Sandbox Code Playgroud)
这会将输出打印到STDOUT并将相同的输出写入日志文件.有关man tee更多信息,请参阅
请注意,这不会将stderr写入日志文件,因此如果要组合这两个流,请使用:
exec 1 2>&1 | tee ${LOG_FILE}
Run Code Online (Sandbox Code Playgroud)
alf*_*onx 32
我尝试了joonty的答案,但我也得到了答案
执行官:1:未找到
错误.这对我来说最有效(确认也适用于zsh):
#!/bin/bash
LOG_FILE=/tmp/both.log
exec > >(tee -a ${LOG_FILE} )
exec 2> >(tee -a ${LOG_FILE} >&2)
echo "this is stdout"
chmmm 77 /makeError
Run Code Online (Sandbox Code Playgroud)
之后的文件/tmp/both.log包含
this is stdout
chmmm command not found
Run Code Online (Sandbox Code Playgroud)
除非从tee中删除-a,否则将附加/tmp/both.log.
提示:>(...)是一个流程替代.它让exec到tee命令,好像它是一个文件.
我想在标准输出和日志文件上显示日志以及时间戳。以上答案都不适合我。我使用了进程替换和exec命令并想出了以下代码。示例日志:
2017-06-21 11:16:41+05:30 Fetching information about files in the directory...
Run Code Online (Sandbox Code Playgroud)
在脚本顶部添加以下几行:
LOG_FILE=script.log
exec > >(while read -r line; do printf '%s %s\n' "$(date --rfc-3339=seconds)" "$line" | tee -a $LOG_FILE; done)
exec 2> >(while read -r line; do printf '%s %s\n' "$(date --rfc-3339=seconds)" "$line" | tee -a $LOG_FILE; done >&2)
Run Code Online (Sandbox Code Playgroud)
希望这对某人有帮助!
小智 5
对于日志文件,您可以输入文本数据。以下代码可能有帮助
# declaring variables
Logfile="logfile.txt"
MAIL_LOG="Message to print in log file"
Location="were is u want to store log file"
cd $Location
if [ -f $Logfile ]
then
echo "$MAIL_LOG " >> $Logfile
else
touch $Logfile
echo "$MAIL_LOG" >> $Logfile
fi
Run Code Online (Sandbox Code Playgroud)
输出: 2. 日志文件将在第一次运行时创建,并在下次运行中不断更新。如果将来运行时日志文件丢失,脚本将创建新的日志文件。