Removing leading zeros before passing a shell variable to another command

前端 未结 14 1244
长情又很酷
长情又很酷 2020-12-08 18:52

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

14条回答
  •  春和景丽
    2020-12-08 19:13

    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.

提交回复
热议问题