tee - 如果文件不存在什么都不做

tee - if file doesn't exist do nothing

我尝试将 echo 命令保存到日志文件:

echo "XXXXX" | tee -a ./directory_with_logs/my_script.log

文件my_script.log存在时效果很好

XXXXX

(XXXXX 也被写入 my_script.log)

当 my_script.log 不存在时,我得到了这样的东西

tee: ./directory_with_logs/my_script.log: No such file or directory
XXXXX

我试过 if else 过程来检查文件是否存在然后写入日志

function saveLog(){ 
if [[ -e "./directory_with_logs/my_script.log" ]] ; then 
tee -a ./directory_with_logs/my_script.log 
fi ; } 
echo "XXXXX" | saveLog

但当文件不存在时它也会出错,xterm 中没有任何反应,没有 echo 命令

如何在 xterm 中打印并写入日志文件 echo 命令,

或者当日志文件不存在时只在 xterm 中打印?

请帮忙:)

您不需要 tee 来附加文件,这就是 >> 的用途

试试这个:

echo "XXXXX" >> ./directory_with_logs/my_script.log

您的代码不起作用的原因是,当文件不存在时,它不会使用标准输入。您可以通过在 else 分支中添加 cat 调用来修复它,如下所示:

saveLog() { 
  if [[ -e "./directory_with_logs/my_script.log" ]] ; then 
    tee -a ./directory_with_logs/my_script.log 
  else
    cat
  fi 
}