bash - 期望的整数表达式

时间:2017-05-18 10:20:16

标签: bash case

我想模拟一台自动售货机,只有在里面扔2欧元才可以买东西。

只要我输入整数值,它就可以工作,但是如果我输入一个字符或浮点数,它会突然停止工作。并抛出一个错误,预期有一个整数表达式。

ang.directive("directive", function() {
    return {
        controller: "{{controller}}",
        link: function (scope, elem, attrs) {
            $scope.controller = "[CONTROLLER NAME]"
        }
    }
});

3 个答案:

答案 0 :(得分:2)

-ne 执行整数比较,因此$x必须扩展为shell识别为整数的内容。只需切换到!=并比较为字符串。此外,由于bash也无法添加浮点值,因此您需要使用bc之类的内容来添加。

while [ "$x" != 2 ] ;
do
  case $x in
        0.5)
                read -p "more money" z
                x=$( bc <<< "$x + $z" )
                ;;
        1)
                read -p "more money" z
                x=$( bc <<< "$x + $z" )
                ;;
        1.5)
                read -p "more money" z
                x=$( bc <<< "$x + $z" )
                ;;
        "R")
                echo "return x"
                x=0
                ;;
        ?)
                echo "enter something else!"
                x=0
                ;;
  esac
done

答案 1 :(得分:0)

一种方法是使用正则表达式,如下所示:

re='^[0-9]+$'
if ! [[ $yournumber =~ $re ]] ; then
   echo "error: Not a number" >&2; exit 1
fi

答案 2 :(得分:0)

Bash只能用整数算术,如stated in the manual

要进行浮点运算,您需要做一些像管道bc这样的事情:

$ x=1.0; z=0.5
$ bc <<< "$x + $z"
1.5

比较工作,有点,你需要读取输出以获得真值:

$ bc <<< "$x < 1.5"
1

其他选择是将浮点数转换为另一个内部表示,例如计算美分而不是全部美元/欧元。 或者将脚本转换为类似zsh,awk或Perl的东西,它们可以处理浮点数。

这是一个基于分数计算的草图:

#!/bin/bash
total=0
getcoin() {

        read -p "Insert coin: " x
        case $x in
        0.1)    cents=10 ;;
        0.2)    cents=20 ;; 
        0.5)    cents=50 ;;
        1|1.0)  cents=100 ;;
        2|2.0)  cents=200 ;;
        *)      echo "Invalid coin!"; return 0;;
        esac
        (( total = total + cents))
        return 0;
}

while getcoin && [[ $total -lt 200 ]] ; do
        printf "You have %d cents\n" "$total"
done
printf "You got %d.%02d € in total\n" $((total / 100)) $((total % 100))
相关问题