0

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.

2 Answers 2

2

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

sed -i "1s/$/ $(hostname | tr '\n' ' ')/" /etc/hosts
Sign up to request clarification or add additional context in comments.

Comments

0

You could use something like

echo "`cat /etc/hosts` `hostname`"

You might be able to write that straight back to /etc/hosts but I'd rather write it to a temporary file and then replace /etc/hosts with that.

If you want no new line at the end of the file, use

echo -n

instead.

This assumes that you want to append to the last line in the file.

1 Comment

If I wanted a single line command to accomplish this method how would I do it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.