2016-09-15 50 views
1

我一直试图让bash脚本在终端和日志文件上输出不同的东西,但我不确定使用什么命令。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摘要...”),而在终端中显示它。有没有这样的命令?如果可以提供一个通用的解决方案而不是特定的解决方案,这将是非常好的,因为我想将其应用于其他脚本。 EDIT 1(之后施加> & 6)

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

欢迎的网站!不要忘了查看[tour](https://stackoverflow.com/tour)了解更多特定于站点的详细信息(以及徽章:))。 – cxw

回答

0

一个选项:

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 ------------^^^ 

>&6发送echo的输出到保存的文件描述符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

尝试肮脏的黑客:

#... 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 
+0

它工作但由于某种原因,最后的回声输出在终端中向上移动。我也使用4.3.46 :( – Larrrrrrrrrry

+0

@Larrrrrrrrrry请[编辑你的问题](http://stackoverflow.com/posts/39515426/edit)包括更多的细节,或者也许是一个截图 - 你是什么意思通过“在终端中向上移动”? – cxw

+0

我编辑我的帖子,在编辑1下。说“总结...”的输出向上移动而不是最后一个输出 – Larrrrrrrrrry

相关问题