: $myvar
ise
expr string : regex ## returns length of string if both sides match
veya Örneğin
expr match string regex ## behaves the same
test etmek için birlikte diyebiliriz tüm haneler:
[ $(expr "x$myvar" : "x[0-9]*$") -gt 0 ] && echo "all digits"
Not: Boş dize atma hatası testine karşı korumak için'x'
değişkenine ve ifadeye eklenmiştir. Test tarafından döndürülen length
'u kullanmak için, 'x'
'u temsil eden 1
'u çıkarmayı unutmayın.
#!/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
Sonuç
$ sh testdigits.sh 265891
'265891' : all digits, length: 6 chars
$ sh testdigits.sh 265891t
'265891t' : contains characters other than [0-9]
darbe normal ifade testi [[ $var =~ ^[0-9]+$ ]]
: if-then-else
formda
, burada komut ilk bağımsız içeren tüm basamak test eder kısa script iyi, kullanıyorum ama bashism (bash kabuğuyla sınırlı). Taşınabilirlik ile ilgileniyorsanız, POSIX testi herhangi bir POSIX uyumlu kabukta çalışır.
'[[$ MyVar = ~ [0-9]]]' bu aynı mı? – 3kstc
1.) '$ MyVar = ~ [0-9]' MyVar içinde en az bir basamak için test eder. Hedefinizi anladığımdan, _all_ basamak olup olmadığını öğrenmek istersiniz. Bu yüzden benim ters formum. 2.) '[0-9]' çalışmak için kullanılır. Modern unicode ile güvenemezsiniz. Bu yüzden kullanıyorum [: digit:] ' – John1024