我在Linux控制台上打招呼;我想用整数变量
创建if
语句
if[$x= [$#-2]]
但是如果can't find this statment if[1 = [5-2]]
,控制台会收到
请帮助我并纠正我的陈述。
答案 0 :(得分:3)
您需要算术扩展:$((expression))
if [ $x = $(($# - 2)) ]; then
# ^ ^ ^ ^ ^ spaces are mandatory
答案 1 :(得分:0)
开始$#
是传递给bash脚本的参数数量
./bash_script 1 2 3
$#
自动魔法填充到3.我希望你已经知道了。
#!/bin/bash
x=1
#If you are trying to compare `$x` with the value of the expression `$# - 2` below is how you do it :
if (( $x == $# - 2 ))
then
echo "Some Message"
fi
#If you are trying to check the assignment to `$x was successful below is how you do it :
if (( x = $# - 2 ))
then
echo "Some Message"
fi
第二个条件几乎总是如此,但第一个条件可能是假的。 以下是我的测试结果:
#Here the both ifs returned true
sjsam@WorkBox ~/test
$ ./testmath1 1 2 3
Some Message
Some Message
#Here the first if returned false because we passed 4 parameters
sjsam@WorkBox ~/test
$ ./testmath1 1 2 3 4
Some Message