bash WHILE 循环 - 逐行读取文件行 - 不工作文件中包含行的次数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16328109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WHILE loop - read line of a file one by one -- Not working the No. of times the file has lines in it
提问by AKS
I'm using a "while" loop within a shell script (BASH) to read line of a file (one by one) -- "Fortunately", its not working the No. of times the file has lines in it.
我在 shell 脚本 (BASH) 中使用“while”循环来读取文件的一行(一个接一个)——“幸运的是”,它不起作用,文件中有行的次数。
Here's the summary: $ cat inputfile.txt
这是摘要: $ cat inputfile.txt
1
2
3
4
5
Now, the shell script content is pretty simple as shown below:
现在,shell 脚本内容非常简单,如下所示:
#!/bin/bash
while read line
do
echo $line ----------;
done < inputfile.txt;
The above script code works just fine..... :). It shows all the 5 lines from inputfile.txt.
上面的脚本代码工作得很好..... :)。它显示了 inputfile.txt 中的所有 5 行。
Now, I have another script whose code is like:
现在,我有另一个脚本,其代码如下:
#!/bin/bash
while read line
do
echo $line ----------;
somevariable="$(ssh sshuser@sshserver "hostname")";
echo $somevariable;
done < inputfile.txt;
Now, in this script, while loop just shows only line "1 ---------" and exits out from the loop after showing valid value for "$somevariable"
现在,在这个脚本中,while 循环只显示“1 ---------”行,并在显示“$somevariable”的有效值后退出循环
Any idea, what I'm missing here. I didn't try using some number N < inputfile.txt and using done <&N way (i.e. to change the input redirector by using a file pointed by N descriptor) .... but I'm curious why this simple script is not working for N no. of times, when I just added a simple variable declaration which is doing a "ssh" operation in a child shell.
任何想法,我在这里缺少什么。我没有尝试使用一些数字 N < inputfile.txt 并使用 done <&N 方式(即通过使用 N 描述符指向的文件来更改输入重定向器)......但我很好奇为什么这个简单的脚本不是为 N 号工作 有时,当我刚刚添加了一个简单的变量声明时,它在子 shell 中执行“ssh”操作。
Thanks.
谢谢。
回答by jlliagre
You might want to add the -n
option to the ssh command. This would prevent it to "swallow" your inputfile.txt as its standard input.
您可能希望将该-n
选项添加到 ssh 命令。这将阻止它“吞下”您的 inputfile.txt 作为其标准输入。
Alternatively, you might just redirect ssh stdin from /dev/null, eg:
或者,您可能只是从 /dev/null 重定向 ssh stdin,例如:
somevariable="$(ssh sshuser@sshserver "hostname" </dev/null)";