首页 > 解决方案 > Bash中的浮点计算和“第16行:[:缺少']'”如何在输出中带入小数点

问题描述

我编写了这段代码来获取 bash 中浮点的温度。这给了我一个错误:

line 16: [: missing ']'

这是代码:

#!/bin/bash
echo "Celsius         Fahrenheit"
echo "--------------------------"
counter=0
while [ $counter -le 25 ]:
do
  let "val = ($counter * 9/5) + 32"
  if [ $counter -le 9 ]
  then
    whitespace="               "
  else
    whitespace="              "
  fi
  echo "$counter$whitespace$val"
  ((counter++))
if [[ "$REPLY" =~ ^-?[[:digit:]]*\.[[:digit:]]+$ ]]; then
   echo "'$REPLY' is a floating point number."
fi

done
exit 1

标签: linuxbashshellscripting

解决方案


当它应该是分号 ( ) 时,您while正在使用冒号 ( )::;

#!/bin/bash
echo "Celsius         Fahrenheit"
echo "--------------------------"
counter=0
while [ $counter -le 25 ];
do
  let "val = ($counter * 9/5) + 32"
  if [ $counter -le 9 ]
  then
    whitespace="               "
  else
    whitespace="              "
  fi
  echo "$counter$whitespace$val"
  ((counter++))
if [[ "$REPLY" =~ ^-?[[:digit:]]*\.[[:digit:]]+$ ]]; then
   echo "'$REPLY' is a floating point number."
fi

done
exit 1

输出:

$ /usr/bin/diff old.sh new.sh 
5c5
< while [ $counter -le 25 ]:
---
> while [ $counter -le 25 ];

$ sh old.sh 
Celsius         Fahrenheit
--------------------------
old.sh: line 5: [: missing `]'

$ sh new.sh 
Celsius         Fahrenheit
--------------------------
0               32
1               33
2               35
3               37
4               39
5               41
6               42
7               44
8               46
9               48
10              50
11              51
12              53
13              55
14              57
15              59
16              60
17              62
18              64
19              66
20              68
21              69
22              71
23              73
24              75
25              77

推荐阅读