测试参数为5位整数

时间:2013-01-25 23:39:23

标签: regex linux bash unix

我想测试bash脚本中的参数是否为5位整数。

if [ "$1" == [0-9][0-9][0-9][0-9][0-9] ]; then
    echo "first arg is 5 digits"
else
    echo "not 5 digits"

这对我不起作用,是否有更简单的方法,即使用expr函数?

3 个答案:

答案 0 :(得分:4)

CONDITIONAL EXPRESSIONS点击man bash

if [[ "$1" =~ ^[0-9]{5}$ ]]; then
    echo "first arg is 5 digits"
else
    echo "not 5 digits"
fi

答案 1 :(得分:4)

测试此类表达式时,必须使用双括号。

答案 2 :(得分:0)

case "$1" in
  [0-9][0-9][0-9][0-9][0-9]) echo "first arg is 5 digits" ;;
  *) echo "not 5 digits" ;;
esac