The problem is that you are ending your command on a \ which suggests that the command will continue on the next line. In the first code snippet, that worked since there was nothing after that except the end of the file. However, now that you have added more stuff, your original syntax error is coming back to bite you, and the command you are actually running has become (removing the detail to show the structure):
docker exec [...] > db.dump 2> db.log exit_status=$?
Which is why this simple script reproduces your error:
#!/usr/bin/env bash
echo foo exit_status=$?
if [ exit_status -ne 0 ]; then
echo "An error occured while running mongodump. Exit Status: $exit_status"
fi
Running that results in:
/home/terdon/scripts/foo.sh: line 6: [: exit_status: integer expression expected
Because exit_status=$? was run as part of the previous command, that means that it was simply passed as one more argument to your docker command. You ran docker ... exit_status=$?. This means it was never run as a variable assignment and so the variable exit_status is not set in your environment. Because it is not set, you get that error. It's the same you would get with any random, non-existant variable name. For instance:
$ if [ blahblah -ne 0 ]; then echo whoops; fi
bash: [: blahblah: integer expression expected
Simply remove the trailing \ from your script and it will work:
docker exec -i container sh -c "mongodump --archive" > \
~/dumps/db-$(date + "%d%m%Y").dump 2> \
~/logs/dumps/db-$(date + "%d%m%Y").log
exit_status=$?
if [ exit_status -ne 0 ]; then
echo "An error occured while running mongodump. Exit Status: $exit_status"
fi
Or, since you don't really need a variable, you could simplify (and fix spelling) to:
docker exec -i container sh -c "mongodump --archive" > \
~/dumps/db-$(date + "%d%m%Y").dump 2> \
~/logs/dumps/db-$(date + "%d%m%Y").log
exit_status=$?
if [ $? -ne 0 ]; then
echo "An error occurred while running mongodump. Exit Status: $?"
fi
Or even just:
docker exec -i container sh -c "mongodump --archive" > \
~/dumps/db-$(date + "%d%m%Y").dump 2> \
~/logs/dumps/db-$(date + "%d%m%Y").log ||
echo "An error occurred while running mongodump. Exit Status: $?"