Append line to /etc/hosts file with shell script

前端 未结 7 1739
春和景丽
春和景丽 2021-01-30 08:41

I have a new Ubuntu 12.04 VPS. I am trying to write a setup script that completes an entire LAMP installation. Where I am having trouble is appending a line to the /etc/ho

7条回答
  •  执笔经年
    2021-01-30 09:09

    Insert/Update Entry

    If you want to programmatically insert/update a hosts entry using bash, here's a script I wrote to do that:

    #!/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
    

    The script is intended for use with OS X but would work on linux as well with minor tweaking.

提交回复
热议问题