Getting return codes from scripts run

I have some BASH scripts I want to run on my machines.

If run from the CLI/Terminal, the script works fine.

But as this is run on remote machines I wanted a bit of "feedback" on what is happening.
I added a line at the end thus:

return $?

Which SHOULD return a 0 if all is good, and other numbers if any problems happen.

But NR doesn't seem to like this idea.

This is the node: (Code follows)

[{"id":"317f1809.c0682","type":"exec","z":"e2bd5a4e.5597e8","command":"bash /home/pi/Mine/NR_Backup.sh","addpay":false,"append":"","useSpawn":"false","timer":"","oldrc":false,"name":"Backup","x":1180,"y":610,"wires":[[],[],["3ce8bab2.acdb46"]]}]

Code:

#!/bin/bash
# ---------------------------------------
# Simple backup script v1.0
# ---------------------------------------

# Variables
myDate=`date "+%Y-%m-%d.%H.%M.%S"`
backupFolderName="$myDate"
backupSource="/home/pi/.node-red"
backupDest="/home/pi/Backups/NR"
backupFilter="*.j*"
backupExclude="lost\+found"

# Tell the user what we're working with
echo "The myDate variable contains: $myDate"
echo "A backup of $backupSource/$backupFilter will be made and stored in $backupDest/$backupFolderName"

# Begin backup
rsync -avz --progress $backupSource/$backupFilter --exclude=$backupExclude $backupDest/$backupFolderName

# We're done.
echo "Done!"
return $?

No, I didn't write the script. I'm not that smart.
Mine was a lot simpler.

Anyway.....

Running it in NR this happens:

"{"code":1,"message":"Command failed: bash /home/pi/Mine/NR_Backup.sh\n/home/pi/Mine/NR_Backup.sh: line 24: return: can only `return' from a function or sourced script\n"}"

I'm (obviously - and again) missing something.

Do you have debug nodes attached to all three outputs of the exec node?

Only the bottom one.

But for other things, that seems to work.

The bottom output is the return code..... So...... Isn't that what I want?

You will also notice that there are two "TEST" nodes below there.

One does a good command and one is a bash command of "garbage" which will error.

if I run the first one, I get back a 0
If I run the second one it sends back (not 0) and the other end sees the non-zero return and notifies me the command has/had a problem.

After a bit of digging, I think that is more an O/S problem than NR.

Sorry.

Shall continue digging.

You don't use return to exit a shell script - just as the error message tells you.

You would use exit $?

However, $? is the return code of the last command run. In you script, you are using $? after a call to echo - so will contain the return code of that call. So it won't tell you anything about whether the rsync worked or not.

You'd need to capture the return code of the call to rsync:

# Begin backup
rsync -avz --progress $backupSource/$backupFilter --exclude=$backupExclude $backupDest/$backupFolderName
RC=$?
# We're done.
echo "Done!"
exit $RC
3 Likes

Thanks very much Nick.

I guess I didn't specify that in the bigger picture.