1

I have a loop that will prompt for the sudo password until it gets it correct. The why isn’t relevant, lets just say it’s part of a bigger script and other solutions aren’t appropriate.

until sudo -n true 2> /dev/null; do
  read -s -p "Password:" sudo_password
  sudo -S -v <<< "${sudo_password}" 2> /dev/null
done

This works very well. However, it does not work when inside brackets

until [[ $(sudo -n true 2> /dev/null) ]]; do
  read -s -p "Password:" sudo_password
  sudo -S -v <<< "${sudo_password}" 2> /dev/null
done

I’ve tried this in a myriad of ways, with both loops and conditionals. I even went so far as doing

until [[ $(sudo -n true 2> /dev/null; echo "$?") -ne 0 ]]; do
  read -s -p "Password:" sudo_password
  sudo -S -v <<< "${sudo_password}" 2> /dev/null

  # check exit status is indeed 0
  sudo -n true 2> /dev/null
  echo "$?"
done

This also does not work, and I do not understand why. Actually, this case always returns 0 (according to the last echo "$?") even if the password is wrong, but it never jumps out of the loop, even if the password is correct, which is even weirder.


Edit: Just realised why the last one didn’t work, while it seemed to in other cases. With that particular comparison, it should’ve been while, not until.

1 Answer 1

2

step by step.

  1. until sudo -n true 2> /dev/null; do this evaluate sudo -n true, discard standard error, and provide return code to until.

  2. $(sudo -n true 2> /dev/null) this

    2.1 evaluate sudo -n true,

    2.2 discard standard error 2> /dev/null

    2.3 take standard output empty

  3. until [[ $(sudo -n true 2> /dev/null) ]]; do this

    3.1-3.3 same as above

    3.4 use [[ empty ]] this is most likely an error

  4. until [[ $(sudo -n true 2> /dev/null; echo "$?") -ne 0 ]]; do this

    4.1 to 4.4 same as above

    4.5 compare empty to 0

The first line is the corret one, sudo provide a return code, simply use it.

A common error is to mistake the return code: an integer (usualy 0 or 1 or 2 (No such file or directory)), with ouput (can be anything, text or binary).

Shells (bash/dash/whateversh) can be told to watch return code (set -e), or in test.

1
  • “A common error is to mistake return code an integer (usualy 0 or 1 or 2 (No such file or directory), with ouput (can be anything, text or binary)” That is a good insight, and explains the issue well, thank you.
    – user137369
    Oct 20, 2015 at 10:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .