Search code examples
linuxbashnetworkingiproute

Get Subnet mask in Linux using bash


I am using bash to get the IP address of my machine with that script:

_MyGW="$( ip route get 8.8.8.8 | awk 'N=3 {print $N}' )"

And now I am trying to get the Subnet Mask in this type:

192.168.1.0/24 

But I have no idea how can I do that.


Solution

  • there are couple of ways to achieve this:

    first: to print the mask in format 255.255.255.0, you can use this:

    /sbin/ifconfig wlan0 | awk '/Mask:/{ print $4;} '
    

    second: we can use ip command to get the mask in format 192.168.1.1/24

    ip -o -f inet addr show | awk '/scope global/ {print $4}'