Here is a native function. Call it like reverseip 12.34.56.78
to have it print 78.56.34.12
. Call it like reversed=$(reverseip 12.34.56.78)
to capture the output into a variable.
reverseip () {
local IFS
IFS=.
set -- $1
echo $4.$3.$2.$1
}
set
with a string argument tokenizes this string into $1
, $2
, etc based on the current value of IFS
. So we are breaking up the function's input argument $1
into tokens, which now replace the original $1
, $2
, etc. Because IFS
is a dot, the input value in the original $1
gets split up on dots. The dash --
is a safety measure to signal the end of options to set
, in case the actual value of $1
would start with a dash (without the --
you would then get an "unknown option" error, or, worse, random or even insecure behavior).