How can you run a command in bash over until succe

2019-01-16 02:55发布

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 `passwd`
while [[ "`passwd`" -gt 0 ]]
while [ `passwd` -ne 0 ]]
# ... And much more

But I can't seem to get it to work.

5条回答
老娘就宠你
2楼-- · 2019-01-16 03:05

To elaborate on @Marc B's answer,

$ passwd
$ while [ $? -ne 0 ]; do !!; done

Is nice way of doing the same thing that's not command specific.

查看更多
做自己的国王
3楼-- · 2019-01-16 03:15
while [ -n $(passwd) ]; do
        echo "Try again";
done;
查看更多
做自己的国王
4楼-- · 2019-01-16 03:16
until passwd
do
  echo "Try again"
done
查看更多
干净又极端
5楼-- · 2019-01-16 03:16

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
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.

查看更多
等我变得足够好
6楼-- · 2019-01-16 03:19

you can use an infinity loop

while true
do
  read -p "Enter password" passwd
  case "$passwd" in
    <some good condition> ) break;;
  esac
done
查看更多
登录 后发表回答