Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tee - if file doesn't exist do nothing

Tags:

bash

tee

I try to save echo command to log file:

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

It works well when file my_script.log exist

XXXXX

(XXXXX was written to my_script.log also)

When my_script.log doesn't exist I got something like this

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

I tried if else procedure to check if files exist and then write to log

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

but it works wrong also when file doesn't exist, there nothing happens in xterm, no echo command

How to print in xterm and write to log file echo command,

or only print in xterm when log file doesn't exist?

Please help :)

like image 326
Tomasz Stanik Avatar asked Aug 23 '26 14:08

Tomasz Stanik


1 Answers

The reason your code doesn't work, is that when the file doesn't exist, it does not consume the standard input. You can fix it by adding a cat call in the else branch like this:

saveLog() { 
  if [[ -e "./directory_with_logs/my_script.log" ]] ; then 
    tee -a ./directory_with_logs/my_script.log 
  else
    cat
  fi 
}
like image 164
user000001 Avatar answered Aug 25 '26 11:08

user000001



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!