Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a script running every 5 mins with two exits in a condition clause.

#!/bin/bash
date=$(date +%Y)
if [ $date -eq '2014' ]
then
    echo "Current year is $date"
    exit 0
else
    echo "Current year is not $date"
    exit 2
fi

How could I specify to only write a log when exit 2? Could this be possible in crontab?

5 * * * * /home/user/script.sh >> script.log 2>> script.err

I have understood that " >> script.log " writes all the return of the script and " 2 >> script.err " writes only if the script didn't run correct. So I don't know if there's a chance to write only where exit 2 down the script.

share|improve this question
1  
Fix shebang line. It should be #!/bin/bash. And replace { with ( and } with ) in second line. –  Arkadiusz Drabczyk Jun 20 at 15:25
    
You're right, thank you very much –  tachomi Jun 20 at 15:34
add comment

2 Answers 2

up vote 1 down vote accepted

To write your error to stderr use the 1>&2 redirect:

echo "Current year is not $date" 1>&2

exit [number] is specifying a return code of [number].

See also:

File Descriptors

Standard Streams

All About Redirection

share|improve this answer
    
so this must be near echo line? couldn't be at crontab too? –  tachomi Jun 20 at 15:49
    
@tachomi it has to follow echo because that is what sends the output to stderr. In the crontab you tell stderr where to go with 2>> script.err –  Creek Jun 20 at 16:00
    
so the script doesn't have to have the exit lines am I right? –  tachomi Jun 20 at 16:09
    
@tachomi correct –  Creek Jun 20 at 16:10
    
Ok, perfect, thank you very much! I had one downvote, do you know why this question could be downvoted? –  tachomi Jun 20 at 16:15
show 1 more comment

You could use logger (man logger) because it is running from cron. And you do not really need the exit codes because you are not doing anything with them, at least in the snippet above.

#!/bin/bash
DATE=$(date +%Y)
if [ $DATE -ne '2014' ]; then
    logger -f script.log "Current year is not $date"
fi
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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