Get Subnet mask in Linux using bash

A simple way of doing it for me, was:

IP=$(ifconfig eth0 | grep -w inet | cut -d" " -f10) # device IP, e.g. 11.1.1.43
IP_RANGE=$(echo $IP | cut -d"." -f1-3).0/24 # subnet 11.1.1.0/24

Replace of course eth0 with the right interface diplayed by ifconfig.


A better approach will be:

 ifconfig eth0 | awk '/netmask/{split($4,a,":"); print a[1]}'

You can substitute the eth0 with any other interface you want


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}'