commit: 47ba61f0855b6104d7ab504ac0dbc92740e3cbab
parent: f85980a40cc0d39138e0e363f5430c7e339e2bf5
author: z0noxz <chris@noxz.tech>
date: Tue, 7 Aug 2018 07:45:44 +0200
generalize ip output
1 file changed, 20 insertions(+), 18 deletions(-)
diff --git a/cidr2ip b/cidr2ip
@@ -17,38 +17,40 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'
-cidr2ip() {
+do_cidr2ip() {
+ # variable declaration
cidr=$1
cidr_invert=$((32-cidr))
mask=$((4294967295 >> cidr_invert << cidr_invert))
- base=256
result=""
+ base=256
+ i=0
+ # base convert decimal mask to base-256
while [ "$mask" -ne 0 ]; do
- result=$(printf '%3s%s' $((mask % base)) "$result")
+ result=$(printf '%-4s%s' $((mask % base)) "$result")
mask=$((mask / base))
done
- oct1=${result%?????????}
- oct2=${result%??????}
- oct3=${result%???}
- oct4=${result#?????????}
-
- oct2=${oct2#???}
- oct3=${oct3#??????}
+ # output as an ip
+ for item in $result; do
+ printf '%d' "$item"
+ i=$((i+1))
+ if [ "$i" -lt 4 ]; then
+ printf '.'
+ else
+ printf '\n'
+ fi
+ done
- printf '%d.%d.%d.%d\n'\
- "$oct1"\
- "$oct2"\
- "$oct3"\
- "$oct4"
+ # success
+ return 0
}
-# check if input is a CIDR
+# check if input is a CIDR, then process it
if [ "$1" -eq "$1" ] 2> /dev/null && [ "$1" -le 32 ] && [ "$1" -gt 0 ]; then
- cidr2ip "$1"
- exit 0
+ do_cidr2ip "$1" && exit 0
fi
# if all fails print usage