How can I make this script review that status of commands and exit if any of the fails:

echo JFFS2 Preparation

cd /root

/root/config 1 > /root/formatted

if grep "PAR_JFFS2_FORMATTED = -1" /root/formatted; then
  echo Need to Format MTD2
  rm -f /root/formatted

  flash_eraseall -j /dev/mtd2

  echo Marking file system as formatted
  /root/config 1 1355270400

  mount -t jffs2 -o noatime /dev/mtdblock2 /mnt

  echo "Formmatted" > /mnt/formatted.txt

  mount -t jffs2 -o noatime /dev/mtdblock2 /mnt

Add set -e early in the script, or change the #! line to #!/bin/sh -e, which will have the same effect.

This sets the errexit shell option, which means that the script will exit as soon as a command is returning a non-zero exit status, with the following exceptions (taken from the POSIX description of set):

  1. The failure of any individual command in a multi-command pipeline shall not cause the shell to exit. Only the failure of the pipeline itself shall be considered.

  2. The -e setting shall be ignored when executing the compound list following the while, until, if, or elif reserved word, a pipeline beginning with the ! reserved word, or any command of an AND-OR list other than the last.

  3. If the exit status of a compound command other than a subshell command was the result of a failure while -e was being ignored, then -e shall not apply to this command.

An alternative is to add || exit after each command that you'd like to exit after, if they fail. For example

flash_eraseall -j /dev/mtd2 || exit
  • This answer might have worked on another shell, but the HUSH shell is very minimal. Here is the error I was given while trying to use the "-e" setting: /bin/sh: invalid option -- e BusyBox v1.17.4 (2017-02-13 16:44:23 EST) multi-call binary. No help available. – Wayne Taylor Feb 15 '17 at 12:53
  • @WayneTaylor I think you need to say what hush shell you're using. Busybox's sh understands the -e option and set -e. – Kusalananda Feb 15 '17 at 13:03
  • Dear Kusalanand, I specified BusyBox v1.17.4 and hush. There are several shells to choose from including Ash. But hush (2008-07-14), as shown did not support -e. – Wayne Taylor Feb 16 '17 at 17:50

After each command in bash the return code is stored in $? variable. If the command is successful its value should be

echo $?

In case o error the result is non zero and varies depending on the error.

echo $?
  • I am having trouble with the HUSH shell testing the results of $$. I tried: if (($? != 0)); then echo "Can't execute ....error($?)" exit -2 fi But the code always seems to run and even prints error(0). – Wayne Taylor Feb 15 '17 at 12:48

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.