Alex Rivera | Logout

Removing leading zeros before passing a shell variable to another command

Asked 2012-06-20T16:13:06.503
70

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 is simply to create a new variable ($nozero) based on $machinenumber, where leading zeros are stripped away.

$machinenumber is a two-digit number between 01 and 24. Currently it's 09

$machinetype is 74 for now and hasn't caused any problems before.

What I have so far is:

nozero = (echo $machinenumber | sed 's/^0*//')
iptables -t nat -I POSTROUTING -s 10.($machinetype).($nozero).0/24 -j MASQUERADE

While I believe I'm on the right track, the code results in:

ERROR - Unknown string operation
Edit
Report

3 Answers

105

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.

answered 2012-06-21T01:10:23.267
28

No, you make all (alomost all) correct. You just must:

  • remove spaces around =
  • use $() or backticks instead of ()

That would be correct:

 nozero=$(echo $machinenumber | sed 's/^0*//')

Also you must use variables without () around them. You can add "" if you want:

iptables -t nat -I POSTROUTING -s "10.$machinetype.$nozero.0/24" -j MASQUERADE

And of course variables here are not necessary. You can say simply:

iptables -t nat -I POSTROUTING -s "10.$(echo $machinenumber | sed 's/^0*//').$nozero.0/24" -j MASQUERADE
answered 2012-06-20T16:20:44.653
4

I do it by using

awk '{print $1 + 0}'

I like this better than the sed approach as it still works with numbers like 0, 000, and 001.

So in your example I would replace

nozero=$(echo $machinenumber | sed 's/^0*//')

with

nozero=$(echo $machinenumber | awk '{print $1 + 0}' )

answered 2013-04-06T14:47:08.683

Your Answer