通过测试获取命令的执行情况
通过判断我们可以根据测试结果,做出相应的操作
有了测试,就要有获得测试结果的机制,并根据测试结果运行不同的代码段,这样就可以实现程序的流程控制。
1. if判断结构
if是最简单的判断语句,如果测试为真则运行相关代码,其语法结构如下:
if expression; then
command
fi
如下脚本会根据输入的学生成绩打印对应的等级:
[root@docp82 ~]# cat xxx.sh
#!/bin/bash
echo -n "Please input a score"
read score
if [ "$score" -lt 60 ];then
echo "C"
fi
if [ "$score" -lt 80 -a "$score" -ge 60 ];then
echo "B"
fi
if [ "$score" -ge 80 ];then
echo "A"
fi
[root@docp82 ~]# bash xxx.sh
Please input a score 55
C
[root@docp82 ~]# bash xxx.sh
Please input a score 88
A
[root@docp82 ~]# bash xxx.sh
Please input a score 77
B
2. if/else判断结构
if expression; then
command
else
command
fi
判断文件是否存在
[root@docp82 ~]# cat xxx.sh
#!/bin/bash
File=/data/app/file.sh
if [ -e $File ];then
echo "$File exists"
else
echo "$File not exists"
fi
[root@docp82 ~]# bash xxx.sh
/data/app/file.sh not exists
3. if/elif/else判断结构
通过 if/elif/else的语法完成多向选择
if expression1; then
command1
elif expression2; then
Command2
elif expression3; then
Command3
...
fi
改写if脚本
#!/bin/bash
echo -n "Please input a score"
read score
if [ "$score" -lt 60 ];then
echo "C"
elif [ "$score" -lt 80 -a "$score" -ge 60 ];then
echo "B"
else
echo "A"
fi
4. case判断结构
case判断结构也可以用于多种可能情况下的分支选择
case VAR in
var1) command1 ;;
var2) command2 ;;
var3) command3 ;;
...
*) command ;;
esac
其原理为从上到下依次比较VAR和var1、var2、var3的值是否相等,如果匹配相等则执行后面的命令语句,在无一匹配的情况下匹配最后的默认*,并执行后面的默认命令。
#!/bin/bash
OS=$(uname -s)
echo "$OS"
case "$OS" in
FreeBSD) echo "This is FreeBSD" ;;
CYGWIN_NT-5.1) echo "This is Cygwin" ;;
SunOS) echo "This is Solaris" ;;
Darwin) echo "This is Mac OSX" ;;
AIX) echo "This is AIX" ;;
Minix) echo "This is Minix" ;;
Linux) echo "This is Linux" ;;
*) echo "Failed to identify this OS" ;;
esac
[root@docp82 ~]# bash xxx.sh
Linux
This is Linux
用于检测用户的输入中是否含有大写字母、小写字母或者数字的脚本
lianggao@bogon ~ % vim dec.sh
#!bin/bash
read -p "Give me a word:" input
echo -en "you give me some:"
case $input in
*[[:lower:]]*) echo -en "Lowercase";;
*[[:upper:]]*) echo -en "Uppercase";;
*[:digit:]]*) echo -en "Numerical";;
*) echo "unkown input";;
esac
lianggao@bogon ~ % bash dec.sh
Give me a word:gao
you give me some:Lowercase%