算术二进制运算符-gt,-lt给出错误但在shell脚本中工作
我写了这个简单的脚本它也有效,但显示错误
clear echo Enter 1st number read n1 echo Enter 2nd number read n2 echo MUlti is `expr $n1 \* $n2`; if [$n1 -lt $n2] then echo $n1 'is bigger than' $n2 else echo $n2 'is bigger than' $n1 fi
产量
Enter 1st number 5 Enter 2nd number 10 MUlti is 50 ./script.sh: line 7: [5: command not found 10 is bigger than 5
[
是一个内置的命令,也称为test
,并且所有命令至少需要一个空格来将它与命令中的其他单词分开。 [
也可在/usr/bin/[
或/usr/bin/test
作为常规命令使用。
当调用为[
,最终]
的存在是命令的要求,并且对于命令的每个参数都需要它周围的空格。
也就是说,在bash中你应该使用命令[[
,它有一些优势[
,例如支持&&
和||
对于逻辑运算,在-a
和-o
旁边。
此外,要进行整数算术运算和整数之间的比较,最好使用算术扩展$((math operations))
和相应的命令((math ops))
。
通过这些观察,您的脚本可能是:
#!/bin/bash clear echo "Enter 1st number" read n1 echo "Enter 2nd number" read n2 echo "Multi is $((n1 * n2))" if ((n1 > n2)); then echo "$n1 is bigger than $n2" else echo "$n2 is bigger than $n1" fi
记得让它可执行( chmod +x my-script
),然后用./my-script
执行它。
对于bash条件if语句,您需要在条件之前和之后都有一个空格。 你应该看起来像:
if [ $n1 -lt $n2 ]
代替
if [$n1 -lt $n2]
高飞,但那是bash shell。