immaculatecapper
immaculatecapper

Reputation: 3

Bash Script stuck looping

I'm trying to write a script that runs another script which fails rarely until it fails.

Here is the script that fails rarely:

#!/usr/bin/bash

n=$(( RANDOM % 100 ))

if (( n == 42 )) ; then
        echo "$n Something went wrong"
        >&2 echo "The error was using magic numbers"
        exit 1
fi

echo "$n Everything went according to plan"

Here is the script that should run the previous script until it fails:

#!/usr/bin/bash

script_path="/tmp/missing/l2q3.sh"

found=0
counter=0

while (( $found == 0 )); do
        output=(bash $script_path)

        if (( $output == 42 Something went wrong )); then
                found=1
        fi

        ((counter++))

if (( $found == 1 )); then
        echo "Number 42 was found after $counter tries"
fi

done

when I try running the second script I get stuck in an infinite loop saying there is a syntax error on line 11 and that something is wrong with 42 Something went wrong. I've tried with "42 Something went wrong" aswell and still stuck in a loop.

Upvotes: 0

Views: 563

Answers (3)

goe1zorbey
goe1zorbey

Reputation: 83

here are 3 steps to move forward.

  1. add a return value at the end of the first script

exit 0

  1. make your first script has executable rights

$ chmod a+x /tmp/missing/12q3.sh

  1. instead of while loop you may use until, which would run until it returns success i.e. 0

    until /tmp/missing/l2q3.sh; do ((counter++)) done

for other if statements please use square brackets [ single or double [[.

Upvotes: 0

Paul Hodges
Paul Hodges

Reputation: 15273

You can use the program execution as the test for a while/until/if (etc.)

Assuming your script returns a valid 0 error code on success, and nonzero on any other circumstance, then -

$: cat tst
#!/bin/bash
trap 'rm -fr $tmp' EXIT
tmp=$(mktemp)
while /tmp/missing/l2q3.sh >$tmp; do let ++ctr; done 
grep -q "^42 Something went wrong" $tmp &&
  echo "Number 42 was found after $ctr tries"

In use:

$: ./tst
The error was using magic numbers
Number 42 was found after 229 tries

Upvotes: 1

Gilles Quénot
Gilles Quénot

Reputation: 185053

The form (( )) is arithemetic only, so you cannot test a string inside.

To test a string, you have to use the [[ ]] version:

[[ $output == "42 Something went wrong" ]] && echo ok
ok

Upvotes: 1

Related Questions