Removing leading zeros before passing a shell variable to another command

前端 未结 14 1064
长情又很酷
长情又很酷 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:11

    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.

提交回复
热议问题