Search code examples
linuxbashechohostnamehosts

Append Output of Hostname Command to /etc/hosts


I have a server in Amazon Elastic Beanstalk in which the hostname command outputs a hostname that is not a full domain and does not exist in the /etc/host file.

I'm working with some software that for some reason relies on the system hostname to work.

I wanted to append the output of the hostname command to the /etc/hosts file referring to the local machine.

Right now I have a host file that looks like this:

127.0.0.1 localhost localhost.localdomain

I am running a command like this to append to the file.

hostname | tr '\n' ' ' >> /etc/hosts

The issue is that the hostname appends as a newline. Like this:

127.0.0.1 localhost localhost.localdomain
ip-10-0-1-162

I want it to append to the same line.


Solution

  • You can use sed to edit the first line of the file:

    sed -i "1s/$/ $(hostname | tr '\n' ' ')/" /etc/hosts