user3647939
user3647939

Reputation: 11

bash - getting line by line - error caused by pipe?

i was trying to read file servers.txt and ping every line in it. it contains server on each line.

#!/bin/bash
clear
output="pingtest.txt"
for line in < cat "servers.txt"
do 
ping $line >> "$output" 2>&1
done

But the script simply does not work, because of '<' on line 4. What am i doing wrong?

Upvotes: 0

Views: 44

Answers (2)

int80h
int80h

Reputation: 1

If you would like to stick with a for loop you could try this:

#!/bin/bash
clear
output="pingtest.txt"
for line in `cat servers.txt`
do 
    ping -c 1 -W 1 ${line} >> ${output} 2>&1
done

Also, you will want to provide a count and timeout for the ping command.

c : is the amount of times you would like to ping the server

W : is the amount of time to wait for the server to respond

Upvotes: 0

kojiro
kojiro

Reputation: 77137

A for loop loops over what is essentially positional parameters. It does not read from standard input. read reads from standard input.

You want

while read line; do
  …
done < "servers.txt"

This is the very first BASH FAQ.

Upvotes: 3

Related Questions