shell编程之if语句

shell编程之if条件语句

1.if条件语法

1.1 if单分支语法

if  <条件表达式>
  then
    指令
fi

1.2 if双分支语法

if <条件表达式>
  then
    指令
else
    指令集2
fi

1.3 if多分支语法

if <条件表达式1>
  then
    指令1...
elif <条件表达式2>
  then
    指令2...
elif <条件表达式3>
  then
    指令3...
else
    指令4...
fi 

2.if语句案例

2.1 如果不存在/backup目录就创建

if [ -d /backup ]
then
    :
else
    mkdir /backup
fi

2.2 开发Shell脚本判断系统剩余内存的大小,如果低于100MB就提示内存不足,否则提示内存充足。

#!/bin/bash
##############################################################
# File Name: 9.sh
# Version: V1.0
# Author: liu
# Organization: 
# Created Time : 2019-04-12 10:05:31
# Description:
##############################################################
mem=`free -m|awk 'NR==2{print $4}'`
if [ $mem -lt 2000 ]                                                                               
then
    echo "磁盘内存不足"
else
    echo "内存充足"
fi

2.3 分别使用变量定义、read读入及脚本传参方式实现比较2个整数的大小。

[root@ci-node1 scripts]# cat 10.sh 
#!/bin/bash
##############################################################
# File Name: 10.sh
# Version: V1.0
# Author: liu
# Organization: 
# Created Time : 2019-04-12 10:08:16
# Description:
##############################################################
read -p "请输入两个数字:" a b
#判断是否为空
if [ -z "$b" ]
then
    echo "必须输入两个数字"
    exit 1
fi
#判断输入的是否为整数
expr 1 + $a + $b &>/dev/null
if [ $? -ne 0 ]
then
    echo "请输入两个整数"
    exit 2
fi

if [ $a -gt $b ]
then
    echo "$a大于$b"
elif [ $a -eq $b ]
then
    echo "$a等于$b"
elif [ $a -lt $b ]
then
    echo "$a小于$b"
fi

2.4 打印一个菜单如下,当用户选择对应的数字时,就执行对应项的应用

[root@ci-node1 scripts]# cat 11.sh 
#!/bin/bash
##############################################################
# File Name: 11.sh
# Version: V1.0
# Author: liu
# Organization: 
# Created Time : 2019-04-12 10:21:00
# Description:
##############################################################
cat <<EOF
    1.install lamp
    2.install lnmp
    3.exit
EOF
read -p "请输入你的选择:" num
if [ -z "$num" ]
then
    echo "输入不能为空"
    exit 
fi
expr 2 + $num &>/dev/null
if [ $? -ne 0 ]
then
    echo "Usage:$0 {1|2|3}"
    exit 1
fi
if [ $num -eq 1 ]
then
    echo "install lamp"
elif [ $num -eq 2 ]
then
    echo "instll lnmp"
elif [ $num -eq 3 ]
then
    echo "bye"
    exit 2
else
    echo "Usage:$0 {1|2|3}"
    exit 3
fi
posted @ 2019-04-22 08:40  游走在边缘的人  阅读(318)  评论(0编辑  收藏  举报