While loop stops reading after the first line in Bash

后端 未结 4 852
温柔的废话
温柔的废话 2021-01-20 21:13

I have the following shell script. The purpose is to loop thru each line of the target file (whose path is the input parameter to the script) and do work against each line.

4条回答
  •  情话喂你
    2021-01-20 22:16

    More generally, a workaround which isn't specific to ssh is to redirect standard input for any command which might otherwise consume the while loop's input.

    while read -r LINE; do
       let count++
       echo "$count $LINE"
       sh ./do_work.sh "$LINE" 

    The addition of is the crucial point here (though the corrected quoting is also somewhat important; see also When to wrap quotes around a shell variable?). You will want to use read -r unless you specifically require the legacy slightly odd behavior you get without -r.

    Another workaround of sorts which is somewhat specific to ssh is to make sure any ssh command has its standard input tied up, e.g. by changing

    ssh otherhost some commands here
    

    to instead read the commands from a here document, which conveniently (for this particular scenario) ties up the standard input of ssh for the commands:

    ssh otherhost <<'____HERE'
        some commands here
    ____HERE
    

提交回复
热议问题