Get value from config file (/ etc / network / interfaces) for init.d script

I want to get the network address (192.168.42.) From the / etc / network / interfaces file. I'm only interested in the wlan0 interface and it would be nice to check if that section exists below.

In the example interface file "wlan0", the IP address is 192.168.42.1. For init.d script afterwards, I want to replace the last byte (* .1) with * .255. So the IP address should be: "192.168.42.255"

Does anyone know how to read the network address from such a file for an init.d script and replace the last byte?

iface wlan0 inet static
  address 192.168.42.1
  netmask 255.255.255.0

      

Currently I just know how to check if a file exists.

# Check for existence of needed config file and read it
test -r $CONFIGF || { echo "$CONFIGF not existing";
    if [ "$1" = "stop" ]; then exit 0;
    else exit 6; fi; }

      

+3


source to share


1 answer


I would use awk

for this, since it is perfectly readable:

awk -v par="wlan0" '
      /^iface/ && $2==par {f=1}
      /^iface/ && $2!=par {f=0}
      f && /^\s*address/ {print $2; f=0}' file

      

Explanation

  • -v par="wlan0"

    provide the name of the interface you want to check.
  • /^iface/ && $2==par {f=1}

    if the string starts with iface

    and the second value is the specified interface name, set the flag.
  • /^iface/ && $2!=par {f=0}

    if the line starts with iface

    and the second value is NOT the given interface name, clear the flag.
  • f && /^\s*address/ {print $2; f=0}

    If the flag is set and the line starts with address

    , print the second black, being its IP. Then reset the counter (thanks to Etan Reisner for this idea).

Note that this checks that the lines are not commented.

If you want to replace the last one .1

with .255

, you can replace the last condition with something like:

f && /^\s*address/ {ip=$2; sub(".1$", ".255", ip); print ip; f=0}
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

      



Test

Given a file based on your input:

$ cat a
iface eth0 inet static
address xxx.xxx.xxx.xxx
netmask 255.255.255.0

iface wlan0 inet static
address 192.168.42.1
netmask 255.255.255.0

iface eth1 inet static
address yyy.yyy.yyy.yyy
netmask 255.255.255.0

      

It returns:

$ awk -v par="wlan0" '/^iface/ && $2==par {f=1} /^iface/ && $2!=par {f=0} f && /^\s*address/ {print $2; f=0}' a
192.168.42.1

      

And replacing the last part of the ip:

$ awk -v par="wlan0" '/^iface/ && $2==par {f=1} /^iface/ && $2!=par {f=0} f && /^\s*address/ {ip=$2; sub(".1$", ".255", ip); print ip; f=0}' a
192.168.42.255

      

+3


source