Shell script while read line loop stops after the

2019-02-25 10:55发布

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. Now, it seems only work with the very first line in the target file and stops after that line got processed. Is there anything wrong with my script?

#!/bin/bash
# SCRIPT: do.sh
# PURPOSE: loop thru the targets 

FILENAME=$1
count=0

echo "proceed with $FILENAME"

while read LINE; do
   let count++
   echo "$count $LINE"
   sh ./do_work.sh $LINE
done < $FILENAME

echo "\ntotal $count targets"

In do_work.sh, I run a couple of ssh commands.

4条回答
成全新的幸福
2楼-- · 2019-02-25 11:29

ssh -n option prevents checking the exit status of ssh when using HEREdoc while piping output to another program. So use of /dev/null as stdin is preferred.

#!/bin/bash
while read ONELINE ; do
   ssh ubuntu@host_xyz </dev/null <<EOF 2>&1 | filter_pgm 
   echo "Hi, $ONELINE. You come here often?"
   process_response_pgm 
EOF
   if [ ${PIPESTATUS[0]} -ne 0 ] ; then
      echo "aborting loop"
      exit ${PIPESTATUS[0]}
   fi
done << input_list.txt
查看更多
女痞
3楼-- · 2019-02-25 11:31

The problem is that do_work.sh runs ssh commands and by default ssh reads from stdin which is your input file. As a result, you only see the first line processed, because ssh consumes the rest of the file and your while loop terminates.

To prevent this, pass the -n option to your ssh command to make it read from /dev/null instead of stdin.

查看更多
叼着烟拽天下
4楼-- · 2019-02-25 11:49

Use ssh -n ... for running your remote commands via ssh.

查看更多
虎瘦雄心在
5楼-- · 2019-02-25 11:55
#! /bin/bash
cat /root/host.txt | while read LINE
..
..

use ssh -n -o StrictHostKeychecking=no in do_work.sh script

  1. List item
查看更多
登录 后发表回答