如何检查字符串是否只包含数字/数字字符

3ks*_*stc 10 bash

如何检查是否MyVar包含带有BASH语句的数字.按数字我指的是0-9.if

即:

if [[ $MyVar does contain digits ]]  <-- How can I check if MyVar is just contains numbers
then
 do some maths with $MyVar
else
 do a different thing
fi
Run Code Online (Sandbox Code Playgroud)

gil*_*iev 15

这里是:

#!/bin/bash
if [[ $1 =~ ^[0-9]+$ ]]
then
    echo "ok"
else
    echo "no"
fi
Run Code Online (Sandbox Code Playgroud)

ok如果第一个参数仅包含数字,no则打印.你可以用它来调用它:./yourFileName.sh inputValue


Joh*_*024 8

[[ $myvar =~ [^[:digit:]] ]] || echo All Digits
Run Code Online (Sandbox Code Playgroud)

或者,如果您喜欢以下if-then形式:

if [[ $myvar =~ [^[:digit:]] ]]
then
    echo Has some nondigits
else
    echo all digits
fi
Run Code Online (Sandbox Code Playgroud)

在过去,我们会使用[0-9].这种形式不是unicode安全的.现代的unicode-safe替代品是[:digit:].


Dav*_*ica 7

如果您想以符合POSIX的方式进行测试,则可以使用以下任一方法:

expr string : regex        ## returns length of string if both sides match
Run Code Online (Sandbox Code Playgroud)

要么

expr match string regex    ## behaves the same
Run Code Online (Sandbox Code Playgroud)

例如,测试是否$myvar为全数字:

[ $(expr "x$myvar" : "x[0-9]*$") -gt 0 ] && echo "all digits"
Run Code Online (Sandbox Code Playgroud)

注意: 'x'在变量和表达式之前,以防止测试空字符串抛出错误。要使用length测试返回的值,请别忘了减去1代表的值'x'

if-then-else形式上,这是一个简短的脚本,用于测试脚本的第一个参数是否包含所有数字:

#!/bin/sh

len=$(expr "x$1" : "x[0-9]*$")  ## test returns length if $1 all digits
let len=len-1                   ## subtract 1 to compensate for 'x'

if [ $len -gt 0 ]; then         ## test if $len -gt 0 - if so, all digits
    printf "\n '%s' : all digits, length: %d chars\n" "$1" $len
else
    printf "\n '%s' : containes characters other than [0-9]\n" "$1"
fi
Run Code Online (Sandbox Code Playgroud)

示例输出

$ sh testdigits.sh 265891

 '265891' : all digits, length: 6 chars

$ sh testdigits.sh 265891t

 '265891t' : contains characters other than [0-9]
Run Code Online (Sandbox Code Playgroud)

[[ $var =~ ^[0-9]+$ ]]我使用bash正则表达式测试很好,但这是一种bashism(仅限于bash shell)。如果您担心可移植性,则POSIX测试将在任何符合POSIX的外壳中运行。