I am writing a simple bash script on Linux to ping some hosts, e.g.:
ping -c 1 google.com
ping -c 1 amazon.com
...
In my approach, I am loading the hosts from a separate file into an array and then loop over the elements. The problem occurs when calling the ping command with elements from the array. Executing the following script gives me an error message.
#!/bin/bash
IFS=$'\n' read -d '' -r hosts < hostnames.txt
for host in "${hosts[@]}"
do
ping -c 1 ${host}
done
I guess there is something wrong with the syntax, but I couldn't figure it out yet.
while read -r hosts; do ping -c "$host"; done < hostnamesprovided the command in your while loop (ping in this example) does not consume/slurp stdin.IFS=$'\n' read -d '' -r hosts < hostnames.txt: Usereadarray/mapfileinstead.mapfile -t hosts < hostnames.txt. Read more athelp mapfilereadcommand you have will not create an array, just a plain variable containing newline characters. Depending on how you check its contents, it's easy to be misled about what it contains. Usedeclare -p hoststo get a better idea what's actually being stored in the variable/array.