0

This question already has an answer here:

#!/bin/sh

if [ $(ls sample01.log | wc -l) = 1 ]
then
echo "File Found" > lsOutput.log
else
echo "File Not Found" > lsOutput.log
fi

But if sample01.log is not already existing my code already returns the error:

ls: cannot access sample01.log: No such file or directory

And the code will not run anymore. The File Not Found will not be displayed anymore. I wanted to capture that error to file (No such file or directory) so each time such error occurs, it is written and documented on the log file.

Thank you.

marked as duplicate by Mikel, jasonwryan, slm, Hauke Laging, Braiam Mar 1 '14 at 15:32

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Your two questions are basically the same. The answer to both question titles is the same: use 2>>logfile inside the parenthesis. I think we should merge the two questions. – Mikel Mar 1 '14 at 7:43
3

You don't need to parse ls in order to determine if a file exists.

help test would tell you:

  -e FILE        True if file exists.

You could say:

if [ -e sample01.log ]
then
  echo "File Found" > lsOutput.log
else
  echo "File Not Found" > lsOutput.log
fi

If you want to ensure that the file is a regular file, use -f instead:

  -f FILE        True if file exists and is a regular file.

(What you've done also works, but it causes ls to emit an error message (to STDERR) which perhaps leads you into thinking that it doesn't work.)

  • Hi devnull. Thank you very much. This forum really helped me in my wanting to learn shell scripting more. It worked! – user60216 Mar 1 '14 at 5:49
  • Would you also know if I can capture grep errors into file? My question is posted in unix.stackexchange.com/questions/117603/… – user60216 Mar 1 '14 at 5:52
  • @user60216 Note that [ is actually other name for to test. So also if test -f myfile; then ... would work but also test -f myfile && do_something_to myfile is pretty common. – Alois Mahdal Mar 1 '14 at 11:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.