# This is a combination of numbers 1 and 2
int(){ expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null||:; }
如果要在非int上获得非零状态代码,请删除||:(也称为true),但保留;
测试
# Wrapped in parens to call a subprocess and not `set` options in the main bash process
# In other words, you can literally copy-paste this code block into your shell to test
( set -eu;
tests=( 4 "5" "6foo" "bar7" "foo8.9bar" "baz" " " "" )
test(){ echo; type int; for test in "${tests[@]}"; do echo "got '$(int $test)' from '$test'"; done; echo "got '$(int)' with no argument"; }
int(){ printf '%d' ${1:-} 2>/dev/null||:; };
test
int(){ expr 0 + ${1:-} 2>/dev/null||:; }
test
int(){ expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null||:; }
test
int(){ printf '%d' $(expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null)||:; }
test
# unexpected inconsistent results from `bc`
int(){ bc<<<"${1:-}" 2>/dev/null||:; }
test
)
测试输出
int is a function
int ()
{
printf '%d' ${1:-} 2> /dev/null || :
}
got '4' from '4'
got '5' from '5'
got '0' from '6foo'
got '0' from 'bar7'
got '0' from 'foo8.9bar'
got '0' from 'baz'
got '0' from ' '
got '0' from ''
got '0' with no argument
int is a function
int ()
{
expr 0 + ${1:-} 2> /dev/null || :
}
got '4' from '4'
got '5' from '5'
got '' from '6foo'
got '' from 'bar7'
got '' from 'foo8.9bar'
got '' from 'baz'
got '' from ' '
got '' from ''
got '' with no argument
int is a function
int ()
{
expr ${1:-} : '[^0-9]*\([0-9]*\)' 2> /dev/null || :
}
got '4' from '4'
got '5' from '5'
got '6' from '6foo'
got '7' from 'bar7'
got '8' from 'foo8.9bar'
got '' from 'baz'
got '' from ' '
got '' from ''
got '' with no argument
int is a function
int ()
{
printf '%d' $(expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null) || :
}
got '4' from '4'
got '5' from '5'
got '6' from '6foo'
got '7' from 'bar7'
got '8' from 'foo8.9bar'
got '0' from 'baz'
got '0' from ' '
got '0' from ''
got '0' with no argument
int is a function
int ()
{
bc <<< "${1:-}" 2> /dev/null || :
}
got '4' from '4'
got '5' from '5'
got '' from '6foo'
got '0' from 'bar7'
got '' from 'foo8.9bar'
got '0' from 'baz'
got '' from ' '
got '' from ''
got '' with no argument
5条答案
按热度按时间nwlls2ji1#
标准品溶液:
您还可以执行以下操作:
但请注意,这会将
07
视为一个八进制数!(因此07
与7
相同,但010
与10
不同)。ioekq8ef2#
其中任何一个都可以从shell命令行运行。
bc
可能是最直接的解决方案。使用bc:
使用
awk
:使用
perl
:使用
Python
:全部返回
ukxgm1gy3#
一个不局限于OP案例的答案
这个问题的标题把人们引到了这里,所以我决定为其他人回答这个问题,因为OP描述的情况是如此有限。
TL;DR
我最终决定写一个函数。
1.如果要在非int的情况下使用
0
:1.如果要在非int的情况下使用 [empty_string]:
1.如果要查找第一个int或 [empty_string]:
1.如果要查找第一个int或0:
如果要在非int上获得非零状态代码,请删除
||:
(也称为true
),但保留;
测试
测试输出
注意事项
我被送进了这个兔子洞,因为accepted answer与
set -o nounset
(又名set -u
)不兼容yhived7q4#
这应该有帮助。
envsm3lx5#
使用此选项:
等等。