0

I try to have a script to add ips to /etc/hosts, but if it does add a line to /etc/hosts, the line is empty. I guess there is an issue with the variable name exchanged by value into the ["] :

machines=("dell" "pb")
ips=( "192.168.0.70" "192.168.0.60")
n=-1
for nom_machine in "${machines[@]}"
do
        n=$(( $n + 1 ))
        ip_machine=${ips[$n]}
        link=" $ip_machine $nom_machine"
        $(sudo /bin/bash -c  'echo -e $link  >> /etc/hosts')

done

Any idea why this add empty lines to /etc/hosts ?

Romain Jouin
  • 4,448
  • 3
  • 49
  • 79

1 Answers1

0

Variables aren't expanded in single quotes, only double quotes. You also don't need the $(...) around sudo.

sudo bash -c "echo -e $link >> /etc/hosts"

As a script style issue, I would suggest removing the sudo call altogether. Instead, expect the person running the script run it with sudo if they don't have sufficient permissions. Your script would just have:

echo -e "$link" >> /etc/hosts
John Kugelman
  • 349,597
  • 67
  • 533
  • 578