HowTos


Resolve IPs for Servers listed in a file using /etc/hosts

cat $NODEFILE | xargs -L 1 -I xx grep xx /etc/hosts | awk '{print $1}';

The command above is a combination of several Linux commands that are used to extract specific information from the /etc/hosts file.

Here is a step-by-step explanation of what the command does:

  1. cat $NODEFILE: This command reads the contents of the file specified by the environment variable $NODEFILE. This file can contain a list of hostnames or IP addresses.
  2. | xargs -L 1 -I xx grep xx /etc/hosts: This command takes the output from the previous step and passes it as an argument to the grep command. The xargs command is used to execute a command for each line of the input. The -L 1 option specifies that only one line from the input should be used as an argument for each execution of the grep command. The -I xx option specifies that the placeholder xx should be used to represent each argument passed to the grep command. The grep command is then used to search for the specified hostnames or IP addresses in the /etc/hosts file.
  3. awk '{print $1}': This command takes the output from the previous step and uses the awk utility to extract specific columns of data. The '{print $1}' option specifies that the first column of data (which is the IP address in this case) should be printed.

The final output of this command will be a list of IP addresses that correspond to the hostnames or IP addresses specified in the $NODEFILE file and found in the /etc/hosts file.

In summary, the command is a pipeline of multiple commands that are used to extract specific information from a file. The combination of the cat, xargs, grep, and awk commands allows for powerful text processing and manipulation, and this kind of command is a common pattern used in many Linux shell scripts.

*NOTES:$NODEFILE contains a list of Hostnames that you want their IPs resolved.
xargs is used to get each Hostname and use on its own as a filter for the grep command that will parse the /etc/hosts file. In other words for each hostname the commands xx grep xx /etc/hosts | awk ‘{print $1}’ are issued. Also it is important to explain what xx is: xx is a variable name that we use, in order to show to the grep command where and how we want it to use the hostname that we got from the /etc/hosts file.
awk is removing all columns but the first where the IPs should be listed there.