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
$ ls foo
ls: cannot access foo: No such file or directory
$ sh test.sh 

My test.sh:


notify() {
echo ${EXIT_CODE}

2 Answers 2


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:

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

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.

  • I found that doing echo 0 helped in my case. Zero means success AFAIK.
    – Tomachi
    Jan 12, 2023 at 9:51

You must log in to answer this question.

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