4

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 :)

Tomasz Stanik
  • 73
  • 1
  • 5
  • 1
    Is the issues that the *file* doesn't exist or that the *directory* doesn't? Because those aren't the same thing. `tee` should create the file just fine but it will not create the directory. – Etan Reisner Jul 15 '15 at 15:16
  • 2
    That's it. Also related [use tee command to redirect output to a file in a non-existent dir](http://stackoverflow.com/q/14236621/1983854). – fedorqui Jul 15 '15 at 15:18
  • Also, what's wrong with simply doing `echo "XXXXXX" >> ./directory_with_logs/my_script.log`??? Why invoke `tee` at all? – twalberg Jul 15 '15 at 16:33

2 Answers2

3

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 
}
user000001
  • 32,226
  • 12
  • 81
  • 108
-5

You don't need tee to append a file thats what >> is for

try this:

echo "XXXXX" >> ./directory_with_logs/my_script.log
pcwizz
  • 142
  • 7