在将shell变量传递给另一个命令之前,删除前导零 [英] Removing leading zeros before passing a shell variable to another command

查看:421
本文介绍了在将shell变量传递给另一个命令之前,删除前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

事实证明iptables不能很好地处理前导零.由于所使用的$machinenumber必须具有前导零以用于其他目的,因此该想法只是基于$machinenumber创建一个新变量($nozero),其中前导零被去除了.

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是介于01和24之间的两位数字.当前为09

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

$machinetype现在是74,以前没有引起任何问题.

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

到目前为止,我有:

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

推荐答案

前几天,由于一些无关的东西,以及与读取相同脚本的其他软件的兼容性,我不得不重新访问此代码.将其重写为最简单的方法,仍然应该是有效的bash:

I had to revisit this code the other day due to some unrelated stuff, and due to compatibility with some other software that reads the same script, i found it a lot easiest to rewrite it into this, which should still be valid bash:

iptables -t nat -I POSTROUTING -s 10.($machinetype).($machinenumber + 0).0/24 -j MASQUERADE

基本上,加0会将其强制解释为整数,因此会自动去除前导零

Basically, adding 0 forces it to be interpreted as an integer, hence automatically stripping the leading zeros

这篇关于在将shell变量传递给另一个命令之前,删除前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆