When I try and save the file to hosts2.yml, it looks like echo is printing to STDOUT. Is there anyway to pass the result of echo to awk, or maybe a better way to do this?
You can make awk print the text instead of using the echo -keyword. The BEGIN-clause in awk is for that: whatever is in the BEGIN clause is executed before any text from the input file is processed:
This should do the same as the construct with echo . Furthermore, a little hint: if you connect two commands (like the awk and the echo ) with the && operator you effectively say: execute the second command only if the first command exits without error.
This can make sense if the second command really depends on the successful execution of the first. But even in this case it is clearer to write it in long form:
if command1 ; then
command2
else
echo "something went wrong with command 1"
fi
instead of the (basically equivalent but less readable)
command1 && command2 || echo "something went wrong with command 1"
In case of awk and echo it doesn't make any sense because, honestly, how is echo supposed to not succeed?
Note I added 'hi there', should be something else.
If you run a series of commands as a child process and save the all the outputs to a variable, stdout gets written to that variable.
There are other ways to do this, as a matter of taste or readability of code.
As was said earlier, an unconditional ; is simpler than the && .
The command group is smarter than a ( command1; command2 ) sub shell.
Note that the command group requires a ; or a newline before the closing } - while the sub shell does not require it before the closing ) .
BTW, in the previous post the $( ) is a sub shell, too. But all the output is stored in a variable aka memory first - this is far from being efficient.