what you call shortcut
seem to be a kind of alias
or more complex functions
.
for answering you ask, you could:
alias checkCommand="grep '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}'"
echo 23.4.5.1 | checkCommand
23.4.5.1
or
function checkIsIp() {
grep '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}'
}
echo 23.4.5.1 | checkIsIp
There is a bash function that will check for IP (v4) and more this will compute 32bit integer if argument is a valid IP and return a RC > 0
if else:
function check_Is_Ip() {
local IFS=.
set -- $1
[ $# -eq 4 ] || return 2
local var
for var in $* ;do
[ $var -lt 0 ] || [ $var -gt 255 ] && return 3
done
echo $(( ($1<<24) + ($2<<16) + ($3<<8) + $4))
}
than now:
if check_Is_Ip 1.0.0.1 >/dev/null; then echo It is. ;else echo There is not. ;fi
It is.
if check_Is_Ip 1.255.0.1 >/dev/null; then echo It is. ;else echo There is not. ;fi
It is.
if check_Is_Ip 1.256.0.1 >/dev/null; then echo It is. ;else echo There is not. ;fi
There is not.
and useable for IP calculation:
There is the back function:
int2ip() {
echo $(($1>>24)).$(($1>>16&255)).$(($1>>8&255)).$(($1&255))
}
check_Is_Ip 255.255.255.0
4294967040
check_Is_Ip 192.168.1.31
3232235807
int2ip $((4294967040 & 3232235807))
192.168.1.0
So as a good practice, you could:
function die() {
echo "Error: $@" >&2
exit 1
}
netIp="192.168.1.31"
netMask="255.255.255.0"
intIp=$(check_Is_Ip $netIp) || die "Submited IP: '$netIP' is not an IPv4 address."
intMask=$(check_Is_Ip $netMask) || die "Submited Mask: '$netMask' not IPv4."
netBase=$(int2ip $(( intIp & intMask )) )
netBcst=$(int2ip $(( intIp | intMask ^ ( (1<<32) - 1 ) )) )
printf "%-20s: %s\n" \
Address $netIp Netmask $netMask Network $netBase Broadcast $netBcst
Address : 192.168.1.31
Netmask : 255.255.255.0
Network : 192.168.1.0
Broadcast : 192.168.1.255
Where check, validation and conversion of inputs are done is only one operation:
intMask=$(check_Is_Ip $netMask) || die "Submited Mask: '$netMask' not IPv4."
If $netMask
don't match IPv4, the command check_Is_Ip
will fail, then die
will be executed. If else, result of conversion will be stored in intMask
variable.