Se sei in Mac o hai bisogno dell'autorizzazione sudo per questo, prova questo:
sudo -- sh -c -e "echo '192.34.0.03 subdomain.domain.com' >> /etc/hosts";
Ti chiederà comunque la password.
modo alternativo da @kainjow
echo '192.34.0.03 subdomain.domain.com' | sudo tee -a /etc/hosts
Assicurati di utilizzare il -i
opzione di sed
.
-i[SUFFIX], --in-place[=SUFFIX]
edit files in place (makes backup if extension supplied)
sed -i "2i192.241.xx.xx venus.example.com venus" /etc/hosts
Altrimenti,
echo "192.241.xx.xx venus.example.com venus" >> /etc/hosts
aggiungerebbe la riga alla fine del file, che potrebbe funzionare come previsto.
Inserisci/aggiorna voce
Se vuoi inserire/aggiornare in modo programmatico una voce hosts usando bash, ecco uno script che ho scritto per farlo:
#!/bin/bash
# insert/update hosts entry
ip_address="192.168.x.x"
host_name="my.hostname.example.com"
# find existing instances in the host file and save the line numbers
matches_in_hosts="$(grep -n $host_name /etc/hosts | cut -f1 -d:)"
host_entry="${ip_address} ${host_name}"
echo "Please enter your password if requested."
if [ ! -z "$matches_in_hosts" ]
then
echo "Updating existing hosts entry."
# iterate over the line numbers on which matches were found
while read -r line_number; do
# replace the text of each line with the desired host entry
sudo sed -i '' "${line_number}s/.*/${host_entry} /" /etc/hosts
done <<< "$matches_in_hosts"
else
echo "Adding new hosts entry."
echo "$host_entry" | sudo tee -a /etc/hosts > /dev/null
fi
Lo script è pensato per l'uso con OS X ma funzionerebbe anche su Linux con piccole modifiche.