0

I want to write a bash script that continually runs a program over and over incrementing the first four digits by one each time until the output of the program changes from one thing to another.

For example:

./exampleProgram userName 0000-4567-4561-4564

output: Wrong

./exampleProgram userName 0001-4567-4561-4564

output: Wrong

./exampleProgram userName 0002-4567-4561-4564

output: Correct

-Loop terminates

The last three sets of four digits will stay constant, it's only the first four that change so the worst case scenario is about 10,000 loops.

2 Answers 2

1

Just loop over the integers, and use something like printf to produce a correctly formatted argument. For example

 for ((i=0; i < 10000; i++)); do
     printf -v sn '%04d-4567-4561-4564' "$i"
     ./exampleProgram userName "$sn"
 done
Sign up to request clarification or add additional context in comments.

2 Comments

For some reason I am still asked for input on the command line when I use this. Could this be the way the program is set up? So as to discourage loops like this from bruteforcing a result? I am still in the loop of the script because I don't have to run it over and over again but I am prompted to enter stuff each time.
It's impossible to say without knowing what exampleProgram is.
0

For example:

exampleProgram() {      #demo
        echo "Debug: $1 $2" >&2
        (($RANDOM % 10)) && { echo "Wrong"; return 1; } || { echo "Correct for $1 $2" ; return 0; }
}

for i in {0000..9999}
do
        res=$(exampleProgram JohnDoe "$i-4567-4561-4564")
        [[ "$res" =~ Correct ]] && break;
done
echo "Loop terminated at ($i) - result $res"

prints

Debug: JohnDoe 0000-4567-4561-4564
Debug: JohnDoe 0001-4567-4561-4564
Debug: JohnDoe 0002-4567-4561-4564
Debug: JohnDoe 0003-4567-4561-4564
Loop terminated at (0003) - result Correct for JohnDoe 0003-4567-4561-4564

If the exampleProgram has different exit status it is better to check it instead of the returned string, like:

    res=$(exampleProgram JohnDoe "$i-4567-4561-4564")
    (( $? )) || break;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.