Skip to content

Instantly share code, notes, and snippets.

@ralavay
Created September 24, 2015 02:30
Show Gist options
  • Select an option

  • Save ralavay/aa57e4bf0b1b9fd2dea0 to your computer and use it in GitHub Desktop.

Select an option

Save ralavay/aa57e4bf0b1b9fd2dea0 to your computer and use it in GitHub Desktop.

Revisions

  1. ralavay renamed this gist Sep 24, 2015. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. ralavay created this gist Sep 24, 2015.
    37 changes: 37 additions & 0 deletions change_hostname.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    #!/bin/bash
    #
    # Change hostname for Ubuntu host

    OLD_NAME=$(hostname)
    echo "- Current hostname is: $OLD_NAME"
    read -p "- Please input new hostname: " NEW_NAME

    update_ect_hostname() {
    sudo hostname $NEW_NAME
    sudo bash -c "echo $NEW_NAME > /etc/hostname"
    }

    update_etc_hosts() {
    # Insert the line "127.0.1.1 <host_name>"" into /etc/hosts
    is_configured=$(grep -E "127.0.1.1.*$NEW_NAME" /etc/hosts)
    if [ "$is_configured" = "" ]; then
    is_set_with_other_name=$(grep -E "127.0.1.1" /etc/hosts)
    if [ "$is_set_with_other_name" = "" ]; then
    sudo sed -i "2i127.0.1.1 $NEW_NAME" /etc/hosts
    else
    sudo sed -i "s/^127.0.1.1.*$/127.0.1.1 $NEW_NAME/g" /etc/hosts
    fi
    fi
    }

    if [ $NEW_NAME = "" ]; then
    echo "- Please enter the new hostname!!"
    exit 1
    fi

    echo "- Updating with new hostname: $NEW_NAME"
    update_etc_hosts
    update_ect_hostname

    echo "- Current hostname is: $(hostname)"
    echo "--- DONE ---"