Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing leading zeros before passing a shell variable to another command

Tags:

bash

strip

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 
like image 882
Jarmund Avatar asked Jun 20 '12 16:06

Jarmund


People also ask

How do I remove leading zeros in bash?

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. $machinetype is 74 for now and hasn't caused any problems before.

How do you remove leading zeros in Linux?

The -Z option of typeset will strip the leading zeros present when used along with -L option. The expression '^0*' will search for a sequence of 0's in the beginning and delete them.

What is ${ 0 * in shell script?

${0} is the first argument of the script, i.e. the script name or path. If you launch your script as path/to/script.sh , then ${0} will be exactly that string: path/to/script.sh . The %/* part modifies the value of ${0} . It means: take all characters until / followed by a file name.

How do you remove leading zeros from a string?

The replaceAll() method of the String class accepts two strings representing a regular expression and a replacement String and replaces the matched values with given String. The ^0+(?! $)"; To remove the leading zeros from a string pass this as first parameter and “” as second parameter.


1 Answers

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.

like image 152
Dennis Williamson Avatar answered Oct 05 '22 22:10

Dennis Williamson