shell Bash脚本陷入循环

von4xj4u  于 2022-12-30  发布在  Shell
关注(0)|答案(3)|浏览(240)

我试图编写一个脚本,运行另一个脚本很少失败,直到它失败。
下面是很少失败的脚本:

#!/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"

下面是应该运行前一个脚本直到失败的脚本:

#!/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

当我尝试运行第二个脚本时,我陷入了一个无限循环,说第11行有语法错误,42 Something went wrong有问题。我也尝试了"42 Something went wrong",但仍然陷入循环。

n6lpvg4x

n6lpvg4x1#

(( ))的形式只能是 arithemetic,所以不能测试里面的字符串。
要测试一个字符串,必须使用[[ ]]版本:

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

bvhaajcl2#

您可以使用程序执行 * 作为 * 测试一段时间/直到/如果(等)
假设您的脚本在成功时返回有效的0错误代码,在任何其他情况下返回非零错误代码,则-

$: 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"

使用中:

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

r1wp621o3#

以下是向前迈进的3个步骤。
1.在第一个脚本的末尾添加返回值
第一个月
1.使您的第一个脚本具有可执行权限
$ chmod a+x /tmp/missing/12q3.sh
1.您可以使用until而不是while循环,它将运行到返回成功(即0)为止
until /tmp/missing/l2q3.sh; do ((counter++)) done
对于其他if语句,请使用方括号[ single or double [[。

相关问题