Append the first half of the first line of /etc/hosts to a conf file I have to edit a config automatically before starting a service in a docker container (a storm supervisor), and I want to append something like this in /opt/storm/conf/storm.yaml: storm.local.hostname: 1.1.1.1 (extracted from /etc/hosts)

What I currently do is that: 

echo -n "storm.local.hostname: " &gt;&gt; /opt/storm/conf/storm.yaml &amp;&amp; head -1 /etc/hosts | awk -F ' ' {'print $1'} | xargs echo &gt;&gt; /opt/storm/conf/storm.yaml


How can I improve on that, on a readability POV? It looks pretty obfuscated to me, but I may just be naive ^^

Disclaimer: this runs inside a docker container, so there's only access to classic bash.
How can I improve on that, on a readability POV? It looks pretty obfuscated to me, but I may just be naive ^^


You're not naive, it looks obfuscated ;-)

A couple of general tips first:


When you find yourself writing the same path twice, put it in a variable


to avoid duplicated hard coded strings
to make it easy to change the path later if needed
to give it a meaningful descriptive name

Avoid echo -n. In general, avoid all echo statements that use any flags like -n, -e, because these are not portable. When you need those extra functions, printf is more portable. Plain echo with no flags, just stuff to print is nice, short and sweet
When you see head and awk in the same pipeline, usually you can rewrite with just awk. It saves the execution of one process.
I think head -NUM is deprecated. To be safe, I suggest to use head -n NUM instead.
To avoid extremely long lines, break the line with a \


A couple of specific tips in the context of your example:


The one-liner first appends some fixed text to the config file,
and then appends some more text by way of awk.
Since awk can print fixed text too, the echo is not needed at all.
xargs seems pointless: you could just redirect the output of awk
The separator ' ' you used with awk seems both unnecessary and error prone. The hosts file might have entries separated by tab. Simply by not specifying a separator, awk will work with both cases, space or tab separated.


Following the suggestions above, the one-liner could be simplified to:

awk '{print "storm.local.hostname: " $1; exit}' &lt; /etc/hosts &gt;&gt; /opt/storm/conf/storm.yaml