1

I want to monitoring cron jobs using shell script. But if I use variable contain exit code of last command I have "0" always. I think it's because I run this script after cron job and "exit code" takes value "0" (start script) How can I ignore start of the script and use "exit code" variable of previous cron job?

$ ls foo ; echo $?
ls: cannot access foo: No such file or directory
2
$ ls foo
ls: cannot access foo: No such file or directory
$ sh test.sh 
0

My test.sh:

#!/bin/bash

notify() {
EXIT_CODE=$?
echo ${EXIT_CODE}
}
notify
1

The exit status of a command is not something that is stored globally in the system; it is kept locally by the shell that executed the command. As soon as the shell executes another command, the previous exit status is lost.

The shell does exit itself with the status of the last command; hence if the last command in a shell script fails, the exit status of the shell is also non-zero.

I don't know how you were thinking that the exit status that was the result of a cron job could be determined in some other random shell session or script; what if there were 20 jobs running in parallel, you are you to find which exit status belongs to what job? Can't be done.

You need to fix the cron job to save its exit status to some status file; then you can read that status file later.

0

You can pass the exit code as a parameter to your script:

ls -l /tmp/filethatdoesnotex.ist
/usr/local/bin/test.sh $?

with test.sh:

RESULT=$1
if [ $RESULT -gt 0 ]
then
   echo "something bad happened and ended with result $RESULT" >&2
else
   echo "everything is fine, sleep on"
fi

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.