while loop to read file ends prematurely

后端 未结 4 1874
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-06 08:29

The eventual goal is to have my bash script execute a command on multiple servers. I almost have it set up. My SSH authentication is working, but this simple while loop is

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-06 08:59

    If you run commands which read from stdin (such as ssh) inside a loop, you need to ensure that either:

    • Your loop isn't iterating over stdin
    • Your command has had its stdin redirected:

    ...otherwise, the command can consume input intended for the loop, causing it to end.

    The former:

    while read -u 5 -r hostname; do
      ssh "$hostname" ...
    done 5

    ...which, using bash 4.1 or newer, can be rewritten with automatic file descriptor assignment as so:

    while read -u "$file_fd" -r hostname; do
      ssh "$hostname" ...
    done {file_fd}

    The latter:

    while read -r hostname; do
      ssh "$hostname" ... 

    ...can also, for ssh alone, can also be approximated with the -n parameter (which also redirects stdin from /dev/null):

    while read -r hostname; do
      ssh -n "$hostname"
    done 

提交回复
热议问题