如何在 bash 中一遍又一遍地运行命令直到成功?
我有一个脚本,想向用户询问一些信息,但在用户填写此信息之前,脚本无法继续。以下是我尝试将命令放入循环中以实现此目的,但由于某种原因它不起作用:
echo "Please change password"
while passwd
do
echo "Try again"
done
我尝试了 while 循环的许多变体:
while `passwd`
while [[ "`passwd`" -gt 0 ]]
while [ `passwd` -ne 0 ]]
# ... And much more
但我似乎无法让它工作。
I have a script and want to ask the user for some information, but 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 `passwd`
while [[ "`passwd`" -gt 0 ]]
while [ `passwd` -ne 0 ]]
# ... And much more
But I can't seem to get it to work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
或者
or
为了详细说明@Marc B的答案,
这是一种很好的方法来完成与命令无关的相同操作。
如果您想将其作为别名来执行此操作(感谢@Cyberwiz):
用法:
To elaborate on @Marc B's answer,
Is a nice way of doing the same thing that's not command specific.
If you want to do this as an alias (kudos to @Cyberwiz):
Usage:
您需要改为测试
$?
,这是上一个命令的退出状态。如果一切正常,passwd 将以 0 退出;如果 passwd 更改失败(密码错误、密码不匹配等),则以非零退出(密码错误、密码不匹配等)。使用反引号版本,您将比较 passwd 的输出,其中会像
输入密码
和确认密码
之类的东西。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...)With your backtick version, you're comparing passwd's output, which would be stuff like
Enter password
andconfirm password
and the like.如果有人希望有重试限制:
If anyone looking to have retry limit:
您可以使用无限循环来实现此目的:
You can use an infinite loop to achieve this:
如果您想要严格模式(
set -e
)并且以上都不起作用,那就有点棘手了。It becomes a little tricky if you want the strict mode (
set -e
) and none of above worked.