UNIX Shell控制结构—IF


流控制(Decision Making)
IF语句有三种格式:
第一种:if ... fi statement

下面是一个实例:

cat if1.sh
#!/bin/sh
a=10
b=20
#①
if [ $a -eq $b ]; then
  echo "a is equal to b";
fi
if [ $a -gt $b ]; then
  echo "a is great than b";
fi
#②
if [ $a -lt  $b ]
then
  echo "a is less than b";
fi
# the EOF

注意:
①条件和处理命令分开的一种写法:
if 条件; then
处理命令
fi
②条件和处理命令分开的另一种写法:
if 条件
then
处理命令
fi
这里需要根据个人习惯去选择。

上面的例子中,变量的值是赋死了的,若要给此脚本传递两个参数,可做如下修改:

cat if1.sh
#!/bin/sh
# a=10
# b=20
if [ $1 -eq $2 ]; then
  echo "the first number is equal to the second";
fi
if [ $1 -gt $2 ]; then
  echo "the first number is great than the second";
fi
if [ $1 -lt  $2 ]
then
  echo "the first number is less than the second";
fi
# the EOF

给脚本传递参数,只需要在sh命令后面添加即可,使用空格隔开:

sh if1.sh 1 2
the first number is less than the second
sh if1.sh 12 1
the first number is great than the second
sh if1.sh 1 1
the first number is equal to the second

  • 1
  • 2
  • 3
  • 下一页

相关内容