atoi() 类似于 bash 中的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12726741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:27:58  来源:igfitidea点击:

atoi() like function in bash?

bash

提问by daisy

Imagine that I use a state file to store a number, I read the number like this:

想象一下,我使用一个状态文件来存储一个数字,我像这样读取这个数字:

COUNT=$(< /tmp/state_file)

COUNT=$(< /tmp/state_file)

But since the file could be disrupted, $COUNT may not contain a "number", but any characters.

但由于文件可能会被破坏,$COUNT 可能不包含“数字”,而是包含任何字符。

Other than using regex, i.e if [[ $COUNT ~ ^[0-9]+$ ]]; then blabla; fi, is there a "atoi" function that convert it to a number(0 if invalid)?

除了使用正则表达式,即if [[ $COUNT ~ ^[0-9]+$ ]]; then blabla; fi,是否有“atoi”函数将其转换为数字(如果无效则为 0)?

EDIT

编辑

Finally I decided to use something like this:

最后我决定使用这样的东西:

let a=$(($a+0))

let a=$(($a+0))

Or

或者

declare -i a; a="abcd123"; echo $a # got 0

declare -i a; a="abcd123"; echo $a # got 0

Thanks to J20 for the hint.

感谢 J20 的提示。

回答by jam

You don't need an atoiequivalent, Bash variables are untyped. Trying to use variables set to random characters in arithmetic will just silently ignore them. eg

您不需要atoi等效项,Bash 变量是无类型的。尝试在算术中使用设置为随机字符的变量只会默默地忽略它们。例如

foo1=1
foo2=bar
let foo3=foo1+foo2
echo $foo3

Gives the result 1.

给出结果1

See this reference

请参阅此参考

回答by loxxy

echo $COUNT | bcshould be able to cast a number, prone to error as per jurgemaister's comments...

echo $COUNT | bc应该能够投射一个数字,根据 jurgemaister 的评论容易出错......

echo ${COUNT/[a-Z]*} | bcwhich is similar to your regex method but not prone to error.

echo ${COUNT/[a-Z]*} | bc这类似于您的正则表达式方法,但不容易出错。

回答by Michael Grieswald

case "$c" in
[0-9])...

You should eat the input string charwise.

您应该按字符方式处理输入字符串。