I run the following file with the > log.log redirector, and it does not capture errors.


echo ************************BEGIN LOG******************************
date +"%m/%d/%Y %H:%M:%S $HOSTNAME"
cp -f /scripts/original/clamscans.log /scripts
find /public/public/clamscans/. -exec grep -n FOUND /dev/null {} \;>>clamscans.log
mail somedude@someplace.com < clamscans.log
tar cvf dailyresults.tar /public/public/clamscans/*.txt
gzip -f dailyresults.tar
mv -f /public/public/clamscans/*.txt /scripts/lastnite
echo end log entry

The following errors show up when I run from the file from the terminal window, but they are not written to log.log:

tar: /public/public/clamscans/*.txt: Cannot stat: No such file or directory
tar: Error exit delayed from previous errors
mv: cannot stat `/public/public/clamscans/*.txt': No such file or directory

What am I doing wrong? I know with Windows you can add the 2>&1 to capture error data. Is there such a thing for Linux?

migrated from stackoverflow.com Sep 27 '10 at 3:39

This question came from our site for professional and enthusiast programmers.

  • command &> filename to redirect both stdout and stderr to file named filename. – Michael Foukarakis Sep 24 '10 at 17:10
  • 2
    I think it is Windows that at some point got redirection similar to what is available in the UNIX shell, not vice versa. – Martin Liversage Sep 24 '10 at 17:13
  • 2
    The funny thing is I had no idea 2>&1 worked on windows, so I thought I read the question wrong at first. Moral of the story: sometimes the equivalent in the other OS is identical. – Karl Bielefeldt Sep 24 '10 at 17:19

File descriptor 1 is stdout, 2 is stderr. This applies to both Linux and Windows. With ">logfile", you're redirecting stdout to the file "logfile", but what you actually want is to redirect stderr. That can be done with "2>filename" or "2>&1" (in combination with ">logfile") on both Windows and Linux, but note that the order might be significant, so it should be "command >logfile 2>&1" and not the other way round.

  • I foolishly assumed it couldn't be that easy. Yet, it works just like Windows. I'm surprised someone didn't flame me for this. Hope I didn't just give somebody an idea either... Thanks. – micah Sep 24 '10 at 17:20
  • 2
    At least one difference remains, i.e. when you want to discard stderr. With Unix you do 2>/dev/null while with Windows you do 2>nul - unless you're using cygwin or others. – ott-- Aug 13 '13 at 20:26

You can redirect standard error to a file like this:

mycommand 2> error.log

and you can use the following syntax to redirect both standard output and standard error to a file:

mycommand &> file


mycommand > file-name 2>&1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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