Max
Max

Reputation: 59

I can I echo error message and send it into a log file?

I'm trying to echo the error message as well as writing it in a log file at the same time but I'm not sure how to do it. I've used 1>&2, but it just sends it to the log file and doesn't echo the message. Here's my code:

while read -r username password; do
    egrep "^$username" /etc/passwd >/dev/null
    if [ $? -eq 0 ]; then
        echo "ERROR BLABLAH $DATE" 1>&2 >> /var/log/error.log

Upvotes: 1

Views: 1873

Answers (2)

user8017719
user8017719

Reputation:

Try

echo "ERROR BLABLAH $DATE" | tee -a /var/log/error.log 1>&2

Description:

tee                                    # will repeat the std input.  
    -a  /var/log/error.log             # will append to the error.log file  
                            1>&2       # will send the stdin to stderr.  

Upvotes: 4

Greg Tobkin
Greg Tobkin

Reputation: 41

You want to use the 'tee' command:

NAME
 tee - read from standard input and write to standard  output
 and files
SYNOPSIS
 tee [OPTION]... [FILE]...

e.g.

$echo "Hello world!" | tee test.txt
Hello world!
$cat test.txt
Hello world!

Upvotes: 2

Related Questions