bash中的无效算术运算符错误

时间:2018-11-13 17:54:06

标签: bash floating-point date-arithmetic

我正在尝试在bash上运行以下代码,但是每次遇到错误(无效的算术运算符)时,任何人都可以帮忙

serverless.yml

4 个答案:

答案 0 :(得分:1)

当您在bash中遇到错误时,该该回到打印行调试了。在shebang行之后,将set -x添加到脚本顶部。然后重新运行它。 Bash会告诉你它在做什么。

line 8: 4.18 + 0: syntax error: invalid arithmetic operator (error token is ".18 + 0")

因此,它说它不知道如何解析4.18....之后的部分。这是因为bash实际上不支持小数:Bash C style arithmetic with floating point value

答案 1 :(得分:0)

我已经尝试过此解决方案,并且对我有用

#!/bin/bash

echo $ result

   for i in $(seq 20);
    do
            k=$(python -c "print($i/100)")
            a=$(python -c "print(4.18+$k)")
            b=$(python -c "print($a+0.01)")
            echo $k
            echo $a
            echo $b
            siesta < BiTeI.fdf > out_file  #do the operation
            lineno=939   # set the line number where the data you want to read is in
            newline=$(sed -n "${lineno}p" "out_file") # asign a veriable for the line from the txt file note to change the file name
           echo $newline >> output.txt  # print the line extracted to an out put file note to generate file before adding to it
            sed -i "30s/$a/${b}/" BiTeI.fdf  # update the input file for new parameters for a specific raw


    done  

谢谢

答案 2 :(得分:0)

我不喜欢awk,它可以为您省去一些头痛。

$: cat x
for i in $(seq 20)
do read k a b <<< "$( echo "$i" | awk '{
      k = $1 / 100;
      a = 4.18 + k;
      b = a + 0.01;
      printf "%.2f %.2f %.2f\n", k, a, b;
   }' )"
   echo "i=$i k=$k a=$a b=$b"
done

$: ./x
i=1 k=0.01 a=4.19 b=4.20
i=2 k=0.02 a=4.20 b=4.21
i=3 k=0.03 a=4.21 b=4.22
i=4 k=0.04 a=4.22 b=4.23
i=5 k=0.05 a=4.23 b=4.24
i=6 k=0.06 a=4.24 b=4.25
i=7 k=0.07 a=4.25 b=4.26
i=8 k=0.08 a=4.26 b=4.27
i=9 k=0.09 a=4.27 b=4.28
i=10 k=0.10 a=4.28 b=4.29
i=11 k=0.11 a=4.29 b=4.30
i=12 k=0.12 a=4.30 b=4.31
i=13 k=0.13 a=4.31 b=4.32
i=14 k=0.14 a=4.32 b=4.33
i=15 k=0.15 a=4.33 b=4.34
i=16 k=0.16 a=4.34 b=4.35
i=17 k=0.17 a=4.35 b=4.36
i=18 k=0.18 a=4.36 b=4.37
i=19 k=0.19 a=4.37 b=4.38
i=20 k=0.20 a=4.38 b=4.39

答案 3 :(得分:-1)

如果您确实无法安装“ bc”,则可以尝试将所有数字放大100,这样就无需使用小数点了。

#!/bin/bash
set -x

for i in $(seq 20);
do
        k=$i #$(($i/100)) *100
        a=$((418+$k)) #$((4.18+$k)) *100
        b=$(($a+001)) #$(($a+0.01)) *100

        siesta < BiTeI.fdf > out_file  #do the operation
        lineno=939   # set the line number where the data you want to read is in
        newline=$(sed -n "${lineno}p" "out_file") # asign a veriable for the line from the txt file note to change the file name
        echo $newline >> output.txt  # print the line extracted to an out put file note to generate file before adding to it
        sed -i "30s/$a/${b}/" BiTeI.fdf  # update the input file for new parameters for a specific raw


done