Run and count

The other day I needed to run a command a number of times and see how many times it worked, and how many times it failed (as measured by the return code).

I could have done this in Python, or various other languages, but for this bash seemed like it would provide enough.

(There are other newer shells, but bash is fairly universally available. I should learn fish someday but there's always been something else to tinker with so far...)

I'm sure there are better ways to do it, but this is where I ended up with. 😄

#!/usr/bin/env bash
# Must be run with bash as it uses bash arithmetic.

SUCCESS=0
FAIL=0
if [ $1 == "-n" ] ; then
  shift
  COUNT=$1
  shift
else
  COUNT=10
fi

# Default to printing an update every 10 percent.
INTERVAL=$(($COUNT / 10))
if [ $INTERVAL -eq 0 ] ; then
  INTERVAL=1
fi

CMD="$@"
echo "Running "$CMD" $COUNT times..."
for i in $(seq 1 $COUNT) ; do
  if [ $(($i % $INTERVAL)) -eq 0 ] ; then
    echo -n "$(($i / $INTERVAL))0%... "
  fi
  $CMD 1>/dev/null
  if [ $? == 0 ] ; then
    SUCCESS=$(($SUCCESS + 1))
  else
    FAIL=$(($FAIL + 1))
  fi

  sleep 1
done

echo
echo
echo "Success: $SUCCESS"
echo "   Fail: $FAIL"

Subscribe to Paul Walker

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe