Search code examples
bashrandomsetecholet

bash set -e causing random exit from for loop


The simplified loop below exits at random times when I use the set -e option. If I remove the set -e option it always completes. I would like to use the set -e option if possible but so far I am at a loss as to why it is exiting and why it happens at random loop iterations each time I run it (try it!). As you can see the only commands are let and echo. Why would the let or echo commands return a non-zero code at random times, or is something else going on?

#!/bin/bash

#   Do Release configuration builds so we can set the build parameters

set -e
CFG=Release

for CASE in {0..511}
do

#   CASE [0...511] iterate
#   MMMM [2...255] random test cases
#   NNNN [1..MMMM) random test cases
#   RRRR [0...255] random test cases
#   XXXX [0...255] random test cases
#   DSXX [1...128] random test cases
#   OASM [1...255] random test cases
#   OLSM [1...255] random test cases

    let "MMMM = $RANDOM % 254 + 2"
    let "NNNN = $RANDOM % ($MMMM - 1) + 1"
    let "RRRR = $RANDOM % 256"
    let "XXXX = $RANDOM % 256"
    let "DSXX = $RANDOM % 128 + 1"
    let "OASM = $RANDOM % 255 + 1"
    let "OLSM = $RANDOM % 255 + 1"

    echo CFG = $CFG, CASE = $CASE, MMMM = $MMMM, NNNN = $NNNN, RRRR = $RRRR, XXXX = $XXXX, DSXX = $DSXX, OASM = $OASM, and OLSM = $OLSM

#   Some other stuff (build and test), that is not causing the problem, goes here

done

#   Some other stuff, that is not causing the problem, goes here

exit 0

Solution

  • Append || true to your let commands or use $((...)) for calculations.

    From help let:

    Exit Status: If the last ARG evaluates to 0, let returns 1; let returns 0 otherwise.