我有一个如下所示的小脚本,如果出现问题,输出会在屏幕上突出显示(以红色、黄色等显示)
normal=$(tput sgr0)
red=$(tput setaf 1)
yellow=$(tput setaf 3)
df -h >/dev/null 2>&1 &
xx_pid=$!
sleep 3
if [ `ps -ef| grep $xx_pid | grep -v grep | wc -l` -gt 0 ]; then
kill $xx_pid > /dev/null 2>&1
printf "%-70s %s\n" "${red}df -h response : " " ......... taking more than 30 Seconds to complete, exiting script${normal}" | tee -a $log
exit
else
printf "%-70s %s\n" "df -h response : " " ......... NORMAL (Completed in less than 30sec)" | tee -a $log
fi
但在日志文件中我看到如下垃圾字符([31m 和 (B[m )
[31mdf -h response : ......... taking more than 30 Seconds to complete, exiting script(B[m
有什么方法可以避免这些垃圾字符而不写入日志文件。
答案1
无需使用tee
:您可以将消息分配给变量并printf
那使用颜色,以及然后将消息附加到日志文件:
msg=$(printf "%-70s %s" "df -h response : " " ......... NORMAL (Completed in >
printf "%s%s%s\n" "${red}" "$msg" "${normal}"
printf "%s\n" "$msg" >>$log
而不是
printf "%-70s %s\n" "${red}df -h response : " " ......... taking more than 30 Seconds to complete, exiting script${normal}" | tee -a $log
问题是tee
它只能写入标准输出。你可以对你的脚本做一些事情来单独重定向标准输出,但这很麻烦:
( printf "%-70s %s\n" "df -h response : " " ......... taking more than 30 Seconds to complete, exiting script" | tee -a $log ) | sed -e "s/^/${red}/" -e "s/$/${normal}/"