BASH code convert CIDR to Netmask or vice versa

    • BASH code convert CIDR to Netmask or vice versa

      Recently working on a BASH script requires checking the netmask bits. Honestly I couldn't write something simple to do it... instead, I found this page gave couple code snippets on how to do it.

      Two functions, very simple but complex looking codes.

      Shell-Script

      1. mask2cdr ()
      2. {
      3. # Assumes there's no "255." after a non-255 byte in the mask
      4. local x=${1##*255.}
      5. set -- 0^^^128^192^224^240^248^252^254^ $(( (${#1} - ${#x})*2 )) ${x%%.*}
      6. x=${1%%$3*}
      7. echo $(( $2 + (${#x}/4) ))
      8. }


      Shell-Script

      1. cdr2mask ()
      2. {
      3. # Number of args to shift, 255..255, first non-255 byte, zeroes
      4. set -- $(( 5 - ($1 / 8) )) 255 255 255 255 $(( (255 << (8 - ($1 % 8))) & 255 )) 0 0 0
      5. [ $1 -gt 1 ] && shift $1 || shift
      6. echo ${1-0}.${2-0}.${3-0}.${4-0}
      7. }
      I like cars and taking pictures! 8)