shell编程基础(二)If条件语句

三种语法:

1)单分支语句

if [ -f /etc/hosts ]

then

    echo '文件存在'

fi

2)双分支语句

if [ -f /etc/hosts ] 

then

   echo "文件存在"

else

echo "文件不存在"

   echo "..." >>/tmp/test.log

fi

3)多分支语句

if [ -f /etc/hosts ] 

then

   echo " hosts文件存在"

elif [ -f /etc/host ]

then

   echo " host文件存在"

fi

 

if条件语句小结

  单分支:一个条件一个结果

  双分支:一个条件两个结果

  多分支:多个条件多个结果

 If语句练习

[root@123 /server/scripts]# cat zhengshu02.sh

#!/bin/bash

##############################################################

# File Name: zhengshu01.sh

# Version: V1.0

# Author: oldboy

# Organization: www.oldboyedu.com

# Created Time : 2018-08-06 17:24:40

# Description:

##############################################################

a=$1

b=$2

 

#第一关

expr 1 + $1 + $2 &>/dev/null

if [ $? -ne 0 ]

then

   echo "请输入两个整数"

   exit 1

fi

 

 

#第二关

if [ $# -ne 2 ]

then

   echo "输入错误的整数个数"

   exit 2

fi

 

#第三关

if [ $a -eq $b ]

then

   echo "$a=$b" 

   exit 3

elif [ $a -gt $b ]

then

   echo "$a>$b"

   exit 4

elif [ $a -lt $b ]

then

   echo "$a<$b"

   exit 5

fi

 

[root@123 /server/scripts]# cat panduan.sh

#!/bin/bash

##############################################################

# File Name: panduan.sh

# Version: V1.0

# Author: oldboy

# Organization: www.oldboyedu.com

# Created Time : 2018-08-06 18:28:43

# Description:

##############################################################

 

if [ -d /backup ]

then

    echo "已经存在"

else

    mkdir -p /backup

fi

posted @ 2017-08-14 23:20  绝望的战斗鸡  阅读(226)  评论(0)    收藏  举报