how to avoid grep output empty file

Using grep to print a keyword in a log to the output file

grep -i -n "application" /app/log1.log > L1.log

Now this gives results if it finds application in the log. But also results empty l1 log file where there are no results.

Would like assistance in creating the l1.log only when there are results.


Solution 1:

Now this gives results if it finds application in the log. But also results empty l1 log file where there are no results.

Correct.
Using the ">" redirection operator pre-deletes the target file.

Would like assistance in creating the l1.log only when there are results.

Use a temporary file to capture any number of results and use grep's exit status to determine whether or not it found anything.

TMP_LOG=/tmp/log.$$

grep -i -n "application" /app/log1.log > ${TMP_LOG}

if [ 0 -eq $? ] ; then
  # At least one Match found 
  cat ${TMP_LOG} > L1.log
  rm ${TMP_LOG} 
fi