Home > database >  How to execute a bash command with arguments from array elements?
How to execute a bash command with arguments from array elements?

Time:05-22

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.

CodePudding user response:

You hostnames.txt was generated on a Windows machine?

Your hostnames have trailing \r characters, so the lookups fail.

Try this:

cp hostnames.txt hostnames.txt.bkp
dos2unix hostnames.txt.bkp hostnames.txt

And then run your script again.

If you don't have dos2unix installed and don't want to install it ... maybe you have tr already available. In that case this should do the trick, too:

tr -d '\r' < hostnames.txt.bkp > hostnames.txt
  •  Tags:  
  • bash
  • Related