Bash脚本中的SSH弄乱文件读取

时间:2011-07-05 15:24:29

标签: bash unix

我有一个逐行读取文件的脚本,并根据读取的内容执行操作。它所做的一件事是ssh到远程服务器并获取一些信息。出于某些原因,这完全超出了我的范围,这将停止从文件中读取行。

脚本本质上是(为了简化问题我已经删除了很多内容,所以如果看起来它没有真正做任何事情,请不要担心):

cat $csv | while read line; do
   shopt -s nocasematch
   for j in "${file_list[@]}"; do
      found=0;
      for i in $(ssh some_server "ls /some_path/${line:0:1}/${line:1:1}/$line*"); do
         if [[ $i =~ .*$j$ ]]; then
            echo "do something";
            found=1;
            break;
         fi;
      done;
      if [[ $found -ne 1 ]]; then
         echo "don't have $j";
      fi;
      if [[ $found -ne 1 && $j == '\.pdf' ]]; then
         getPDF $line ${dest};
      fi;
   done;
   shopt -u nocasematch
done

这个脚本最终只能在csv的第一行运行。如果我用其他任何东西替换脚本的“ssh”部分,它会在文件的所有行上一直运行。是什么赋予了?

2 个答案:

答案 0 :(得分:9)

ssh正在消耗stdin。通过-n

答案 1 :(得分:0)

如果在循环内运行从stdin读取的命令(例如ssh),则需要确保:

  • 你的循环不是通过stdin迭代
  • 您的命令已重定向stdin:

前者:

while read -u 5 -r; do
  ssh "$REPLY" ...
done 5<file

...使用bash 4.1或更新版本,可以使用自动文件描述符分配重写,如下所示:

while read -u "$file_fd" -r; do
  ssh "$REPLY" ...
done {file_fd}<file

后者:

while read -r; do
  ssh "$REPLY" ... </dev/null
done <file