Awk throws "No such file or directory error" where using hostname -I

0

This command works fine are print the hostname

awk -v MYHOST=$(hostname) '{printf(MYHOST)}'

However on running

awk -v MYHOST=$(hostname -I) '{printf(MYHOST)}'

throws a

awk: cannot open "ip address" (No such file or directory)

Aninda Choudhary

Posted 2019-12-11T09:47:17.787

Reputation: 1

Yeah . the host has multiple ip addresses . So works with the quotes. – Aninda Choudhary – 2019-12-11T10:09:11.170

Answers

0

You should always use double-quotes around command substitutions. The following command is fixed, it will not throw the error:

awk -v MYHOST="$(hostname -I)" '{printf(MYHOST)}'

With $(hostname -I) unquoted, these are possible outcomes (after expansion):

  • awk -v MYHOST= '{printf(MYHOST)}'
    

    This will formally work.

  • awk -v MYHOST=1.2.3.4 '{printf(MYHOST)}'
    

    This will formally work.

  • awk -v MYHOST=1.2.3.4 5.6.7.8 '{printf(MYHOST)}'
    

    This will treat 5.6.7.8 as a script and {printf(MYHOST)} as a file to be parsed. The error will be like cannot open '{printf(MYHOST)}' (No such file or directory), unless there is such file.

  • awk -v MYHOST=1.2.3.4 5.6.7.8 9.10.11.12 … '{printf(MYHOST)}'
    

    where indicates zero or more additional addresses. This will treat 5.6.7.8 as a script and 9.10.11.12 … '{printf(MYHOST)}' as multiple files to be parsed. The error will mention the first nonexistent "file", e.g. cannot open '9.10.11.12' (No such file or directory).

    This is what happened in your case.

Kamil Maciorowski

Posted 2019-12-11T09:47:17.787

Reputation: 38 429