在 zsh 中,你如何创建一个循环,当命令失败时,它会使用新参数重试相同的命令,直到没有错误触发

In zsh how do you make a loop that when the command FAILS, it retries the same command with new arguments until no error triggered

关于我问这个问题的原因的一些背景信息。我目前正在 python 尝试一些东西,我想利用 os.system() 命令从我拥有的字典文本文件中尝试不同的潜在 wifi 密码,直到成功为止。我曾尝试使用 python 本身来查找使用 TRY/EXCEPT 的错误,但我没有足够的经验知道如何在另一个资源中查找错误并据此指示操作。所以当时我觉得最简单的方法就是说下面的:

for current_pass in PotentialPasswords:
    os.system('networksetup -setairportnetwork en0 {} "{}"'.format(ssid, current_pass))

当然这很糟糕并且导致了很多问题。我尝试了几种变体,直到我意识到 zsh 本身具有循环功能,所以现在我正在研究是否可以有效地告诉 zsh 执行命令,如果该命令失败,请再次尝试相同的命令但是有了新的参数,直到命令成功,在这种情况下我希望循环结束。

for x in pass1 pass2 pass3 pass4; do networksetup -setairportnetwork en0 NETWORK_NAME $x; done

我知道上面的方法行不通,但我希望我至少是在正确的轨道上。任何关于如何实现我的目标的建议或指导将不胜感激!

#!/bin/bash

# Simulate an external command that randomly fails
function external_command {
    if [ $[ $RANDOM %  ] -eq 0 ] ; then
        echo "succeed"
        return 0
    else
        echo "failed"
        return 1
    fi
}

# Iterate over your predefined tests
for i in 2 3 4 5 ; do
    # Retry logic
    while
        echo -n "Trying external_command $i... "
        # Call the external command
        external_command $i
        # $? is the return code, 0 if successful
        [ $? -ne 0 ]
    do true ; done
done

给出如下输出:

Trying external_command 2... succeed
Trying external_command 3... failed
Trying external_command 3... succeed
Trying external_command 4... failed
Trying external_command 4... succeed
Trying external_command 5... failed
Trying external_command 5... failed
Trying external_command 5... failed
Trying external_command 5... failed
Trying external_command 5... failed
Trying external_command 5... failed
Trying external_command 5... failed
Trying external_command 5... succeed

我借鉴了the do..while loop from here的思路。

该解决方案应该适用于 bash/zsh。