Home > Net >  Bash Script stuck looping
Bash Script stuck looping

Time:12-29

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.

CodePudding user response:

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

CodePudding user response:

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
  • Related