0

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

#!/bin/bash

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 [email protected] < 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?

3
  • command &> filename to redirect both stdout and stderr to file named filename.
    – Michael Foukarakis
    Commented Sep 24, 2010 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. Commented Sep 24, 2010 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. Commented Sep 24, 2010 at 17:19

2 Answers 2

3

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.

2
  • 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
    Commented Sep 24, 2010 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--
    Commented Aug 13, 2013 at 20:26
1

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

or

mycommand > file-name 2>&1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .