It turns out that iptables doesn\'t handle leading zeros too well. As $machinenumber
that is used has to have a leading zero in it for other purposes, the idea
You don't need to use sed
or another external utility. Here are a couple of ways Bash can strip the leading zeros for you.
iptables -t nat -I POSTROUTING -s "10.$machinetype.$((10#$machinenumber)).0/24" -j MASQUERADE
The $(())
sets up an arithmetic context and the 10#
converts the number from base 10 to base 10 causing any leading zeros to be dropped.
shopt -s extglob
iptables -t nat -I POSTROUTING -s "10.$machinetype.${machinenumber##+(0)}.0/24" -j MASQUERADE
When extglob
is turned on, the parameter expansion shown removes all leading zeros. Unfortunately, if the original value is 0, the result is a null string.
you can also do
machinenumber=$(expr $machinenumber + 0)
A pure bash solution:
> N=0001023450
> [[ $N =~ "0*(.*)" ]] && N=${BASH_REMATCH[1]}
> echo $N
1023450
I would say you are very close. I do not see a requirement stated for bash, but your nonzero logic is flawed.
nonzero=`echo $machinenumber + 0 | bc`
iptables -t nat -I POSTROUTING -s 10.$machinetype.$nozero.0/24 -j MASQUERADE
Adding 0 is a common method for changing a string number into a non-padded integer. bc is a basic calculator. I use this method for removing space and zero padding from numbers all the time.
While I am not expert in iptables syntax, I am pretty sure the parenthesis are not necessary. Since I already have non-word characters bordering both variables, I do not need special enclosures around them. Word characters are;
[a-zA-z0-9_]
Using this solution, you do not lose zero as a potential value, and should be portable across all shells.
If you are using bash, this looks like the simplest:
nozero=$(bc<<<$machinenumber)
Using sed:
echo 000498 | sed "s/^0*\([1-9]\)/\1/;s/^0*$/0/"
498
echo 000 | sed "s/^0*\([1-9]\)/\1/;s/^0*$/0/"
0