I am trying to write a bash script that will run a second script repeatedly until it fails and capture the stdout and stderr of that second script. I have managed to deal with most problems encountered during the process, and have ended up with this script (called error_checker.sh
):
#!/usr/bin/env bash
i=0
while [ $? -ne 1 ]
do
i=$[$i+1]
source script.sh &> log.txt
echo "This error occurred after $i run(s)." >> log.txt
done
The script I would like to repeat repeatedly is called script.sh
, and has the following code:
#!/usr/bin/env bash
n=$(( RANDOM % 100 ))
if [[ n -eq 42 ]]; then
echo "Something went wrong"
>&2 echo "The error was using magic numbers"
exit 1
fi
echo "Everything went according to plan"
The error_checker.sh
script can output the stdout and stderr of that failed run to a designated file, log.txt, but as the script exits along with the second script at the line
source script.sh &> log.txt
I can not append the additional error message to that file due to this.
I have searched around for a while and found that this might be related to creating subshells when running the second script, which may solve the problem, but I just could not get the script to run using ./
instead of source
. If I changed source
to ./
, the whole terminal just froze when I type in ./error_checker.sh
.
Much appreciated to any helping hand!
UPDATE:
Thanks for the current answers! I think that now my main question is that when I change source script.sh
to ./script.sh
in the error_checker.sh
to run it in a new shell process the whole terminal just froze, which prevents me from using ./
, and that is why I could only run error_checker.sh
successfully when using source script.sh
. Any ideas what happened?
UPDATE II:
I have changed source
to ./
and found that although the whole terminal seems frozen and I had to end the process by pressing ctrl + c, it can still generate a log.txt. However, while the version using source
will generate a log.txt saying
Something went wrong. The error was using magic numbers
, which indicates the stdout and stderr were captured by using &>
, the version using ./
generated a log.txt saying
Everything went according to plan. The error occurred after X run(s)
.
Any idea what happened?
FINAL UPDATE: I have edited my code according to the answer by Glenn to the following and it works perfectly. Seems that the echo command in the while loop has blocked me from actually evaluating the exit status of script.ph, and thus creating an infinite loop.
#!/usr/bin/env bash
i=0
while [ $? -ne 1 ]
do
((i++))
./script.sh >& log.txt
done
echo "This error occurred after $i run(s)." >> log.txt
script.sh
instead of just running it?