Shell学习笔记

一、单分支if语句

1. 语法格式

if [ 条件判断式 ]; then
    程序
fi

或者

if [ 条件判断式 ]
    then
    程序
fi

注意:中括号和条件判断式之间必须有空格

2. 示例1:判断登陆的用户是否是root

#!/bin/bash

if [ "$USER" == root ];then
    echo "Login User is root"
fi

#########或者#########

#!/bin/bash

if [ "$USER" == root ]
    then
    echo "Login User is root"
fi

3. 示例2:判断分区使用率

#!/bin/bash

test=$(df -h | grep sda1 | awk '{print $5}' | cut -d '%' -f 1)

if [ $test -ge 90 ];then
    echo "Warning! /dev/sda1 is full!"
fi

二、双分支if语句

1. 语法格式

if [ 条件判断式 ]; then
    条件成立时,执行的程序
    else
    条件不成立时,执行的程序
fi

或者

if [ 条件判断式 ]
    then
    条件成立时,执行的程序
    else
    条件不成立时,执行的程序
fi

2.  示例1:输入一个文件,判断是否存在

#!/bin/bash

read -p "Please input a file:" file

if [ -f $file ]; then
    echo "File: $file exists!"
else
    echo "File: $file not exists!"
fi

3. 示例2:判断apache服务是否启动了,如果没有启动,就代码启动

#!/bin/bash

test=$(ps aux | grep httpd | grep -v 'grep' | wc -l)

if [ $test -gt 0 ]; then
    echo "$(date) httpd is running!"
else
    echo "$(date) httpd isn't running, will be started!"
    /etc/init.d/httpd start
fi

三、多分支if语句

1. 语法格式

if [ 条件判断式1 ]; then
    当条件判断式1成立时,执行程序1
elif [ 条件判断式2 ]; then
    当条件判断式2成立时,执行程序2
.....省略更多条件.....
else
    当所有条件都不成立时,最后执行此程序
fi

2. 示例:实现计算器

#!/bin/bash

# 输入数字a,数字b和操作符
read -p "Please input number a:" a
read -p "Please input number b:" b
read -p "Please input operator[+|-|*|/]:" opt

# 判断输入内容的正确性
testa=$(echo $a | sed 's/[0-9]//g')
testb=$(echo $a | sed 's/[0-9]//g')
testopt=$(echo $opt | sed 's/[+|-|*|/]//g')

if [ -n "$testa" -o -n "$testb" -o -n "$testopt" ]; then
    echo "input content is error!"
    exit 1
elif [ "$opt" == "+" ]; then
    result=$(($a+$b))
elif [ "$opt" == "-" ]; then
    result=$(($a-$b))
elif [ "$opt" == "*" ]; then
    result=$(($a*$b))
else
    result=$(($a/$b))
fi

echo "a $opt b = $result"

四、case语句

case语句和if...elif...else语句都是多分支条件语句,不过和if多分支条件语句不同的是,case语句只能判断一种条件关系,而if语句可以判断多种条件关系。

1. 语法格式

case $变量名 in
"值1")
    如果变量的值等于值1,则执行程序1
    ;;
"值2")
    如果变量的值等于值2,则执行程序2
    ;;
.....省略其他分支.....
*)
    如果变量的值都不是以上的值,则执行此程序
    ;;
esac

2. 示例:判断用户输入

#!/bin/bash

read -p "Please choose yes/no:" cmd

case $cmd in 
"yes")
    echo "Your choose is yes!"
    ;;
"no")
    echo "Your choose is no!"
    ;;
*)
    echo "Your choose is error!"
    ;;
esac
原文地址:https://www.cnblogs.com/refine1017/p/shell_if.html