如何在 bash 中运行命令直到成功
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5274294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can you run a command in bash over until success
提问by J V
I have a script and want to ask the user for some information, the script cannot continue until the user fills in this information. The following is my attempt at putting a command into a loop to achieve this but it doesn't work for some reason.
我有一个脚本,想向用户询问一些信息,在用户填写这些信息之前,脚本无法继续。以下是我将命令放入循环以实现此目的的尝试,但由于某种原因它不起作用。
echo "Please change password"
while passwd
do
echo "Try again"
done
I have tried many variations of the while loop:
我已经尝试了 while 循环的许多变体:
while `passwd`
while [[ "`passwd`" -gt 0 ]]
while [ `passwd` -ne 0 ]]
# ... And much more
But I can't seem to get it to work.
但我似乎无法让它发挥作用。
回答by Erik
until passwd
do
echo "Try again"
done
or
或者
while ! passwd
do
echo "Try again"
done
回答by Marc B
You need to test $?
instead, which is the exit status of the previous command. passwd
exits with 0 if everything worked ok, and non-zero if the passwd change failed (wrong password, password mismatch, etc...)
您需要改为测试$?
,这是上一个命令的退出状态。passwd
如果一切正常,则以 0 退出,如果 passwd 更改失败(密码错误、密码不匹配等),则以非零退出
passwd
while [ $? -ne 0 ]; do
passwd
done
With your backtick version, you're comparing passwd's output, which would be stuff like Enter password
and confirm password
and the like.
有了您的反引号的版本,你要比较passwd文件的输出,这将是这样的东西Enter password
和confirm password
等。
回答by duckworthd
To elaborate on @Marc B's answer,
详细说明@Marc B的回答,
$ passwd
$ while [ $? -ne 0 ]; do !!; done
Is nice way of doing the same thing that's not command specific.
是做同样的事情的好方法,而不是特定于命令的。
回答by kurumi
You can use an infinite loop to achieve this:
您可以使用无限循环来实现此目的:
while true
do
read -p "Enter password" passwd
case "$passwd" in
<some good condition> ) break;;
esac
done
回答by aclokay
If anyone looking to have retry limit:
如果有人希望有重试限制:
max_retry=5
counter=0
until $command
do
sleep 1
[[ counter -eq $max_retry ]] && echo "Failed!" && exit 1
echo "Trying again. Try #$counter"
((counter++))
done
回答by Andrés Rivas
while [ -n $(passwd) ]; do
echo "Try again";
done;