gpt4 book ai didi

linux - Bash 以不同方式输出到屏幕和日志文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:23:24 29 4
gpt4 key购买 nike

我一直在尝试让 bash 脚本在终端和日志文件上输出不同的内容,但不确定要使用什么命令。

例如,

#!/bin/bash
freespace=$(df -h / | grep -E "/" | awk '{print $4}')
greentext="\033[32m"
bold="\033[1m"
normal="\033[0m"
logdate=$(date +"%Y%m%d")
logfile="$logdate"_report.log

exec > >(tee -i $logfile)

echo -e $bold"Quick system report for "$greentext"$HOSTNAME"$normal
printf "\tSystem type:\t%s\n" $MACHTYPE
printf "\tBash Version:\t%s\n" $BASH_VERSION
printf "\tFree Space:\t%s\n" $freespace
printf "\tFiles in dir:\t%s\n" $(ls | wc -l)
printf "\tGenerated on:\t%s\n" $(date +"%m/%d/%y") # US date format
echo -e $greentext"A summary of this info has been saved to $logfile"$normal

我想在终端中显示日志文件时省略最后的输出(回显“A summary...”)。有命令这样做吗?如果可以提供通用解决方案而不是特定解决方案,那就太好了,因为我想将其应用于其他脚本。

编辑 1(申请后 >&6):

Files in dir:   7
A summary of this info has been saved to 20160915_report.log
Generated on: 09/15/16

最佳答案

一个选项:

exec 6>&1    # save the existing stdout
exec > >(tee -i $logfile) # like you had it
#... all your outputs
echo -e $greentext"A summary of this info has been saved to $logfile"$normal >&6
# writes to the original stdout, saved in file descriptor 6 ------------^^^

>&6echo 的输出发送到保存的文件描述符 6(终端,如果您从交互式 shell 运行它)而不是tee 设置的输出路径(位于文件描述符 1 上)。在 bash 4.3.46 上测试。

引用文献:"Using exec""I/O Redirection"

编辑 正如 OP 发现的那样,>&6 消息不能保证出现在 tee 打印的行之后 stdout。一种选择是使用 script,例如,在 this question 的答案中,而不是 tee,然后在 script 之外打印最终消息。每the docs ,该问题的 stdbuf 答案不适用于 tee

尝试一个肮脏的 hack:

#... all your outputs
echo >&6 # <-- New line
echo -e $greentext ... >&6

或者,同样 hackish,(请注意,根据 OP,这有效)

#... all your outputs
sleep 0.25s # or whatever time you want <-- New line
echo -e ... >&6

关于linux - Bash 以不同方式输出到屏幕和日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39515426/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com