2

There is a program like this:

while true
do
    echo 'Your pass: '
    read password
    if [ $password == 'qwerty' ]; then 
        echo 'Nice!'
        break
    fi
done

I can use xargs only if the program has arguments. But in this case ./program.sh password doesn't work. I have a list of password and I need to send them in loop to this program.

xargs -a list ./program.sh doesn't work.

terdon
  • 234,489
  • 66
  • 447
  • 667
TrueBad0ur
  • 193
  • 1
  • 1
  • 7
  • 2
    Note that this outputs `Nice!` if the user enters `qwerty`, but also if they enter `" qwerty "` (leading or trailing space or tabs with the default value of `$IFS`) or `q\w\e\r\t\y`... See [Understanding "IFS= read -r line"](//unix.stackexchange.com/q/209123), and also if they enter `-d / -o y` as your forgot to quote `$password`. – Stéphane Chazelas Apr 19 '18 at 10:11
  • Besides the quoting issue raised by Stéphane (serious hole, btw, as it doesn't really matter what the password is), it would also be better if you do `stty -echo` before the `read` and `stty echo` after it, so the password is not displayed in the terminal. – JoL Apr 19 '18 at 17:11

1 Answers1

11

There's no reason to use xargs here, you can simply do:

while IFS= read -r password
do
    if [ "$password" = 'qwerty' ]; then 
        echo 'Nice!'
        break
    fi
done

And then run it as:

./program.sh < list

If you really want xargs, you can do something like:

for password do
  case "$password" in
    'qwerty')
      echo 'Nice!'
      ;;
  esac
done

And then:

xargs -rd '\n' -a list ./program.sh
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
terdon
  • 234,489
  • 66
  • 447
  • 667
  • @StéphaneChazelas thanks for the edit, I should have done most of those myself. Why change the `"$@"` though? Is `$@` not portable? And why have them on the same line and without a `;` before `do`? – terdon Apr 19 '18 at 10:23
  • 1
    `for i do` is the Bourne/POSIX<2016 syntax. `for i\ndo` is the most portable if you ever come across ancient BSDs. `for i; do` is now also standard with the 2016 edition of the standard. `for i in "$@"` has a number of issues with a number of shells in corner cases. It's discussed in some Q&A here I beleive. – Stéphane Chazelas Apr 19 '18 at 10:32
  • 2
    Note that neither `-a`, `-r` nor `-d` are standard `xargs` options. – Stéphane Chazelas Apr 19 '18 at 10:33
  • @StéphaneChazelas I'm having trouble finding that Q&A on the issues of `for i in "$@"; do` vs `for i; do`. It sounds very interesting, as I thought they'd have an identical effect. Would you do the favour of linking it for all of us? – JoL Apr 19 '18 at 20:32
  • 1
    @StéphaneChazelas Nevermind. I think I found it [here](https://unix.stackexchange.com/questions/417292/bash-for-loop-without-a-in-foo-bar-part/417296#417296). – JoL Apr 19 '18 at 20:44