-
if语句
if语句的一般格式为:if 测试条件 then 命令1 else 命令2 fi
例如:
if test -f " $1 " then echo " $1 is an ordinary file " else echo " $1 is not an ordinary file" fi
条件测试有两种常用形式:一种用test命令,如上例所示;另一种是用一对方括号将测试条件括起来。这两种形式是完全等价的。即test -f " $1"也可以写成[ -f " $1" ],在格式上需要注意的是,[ ]两端需要有空格。
条件测试常用来测试文件的属性、做字符串的比较和数值的比较。文件测试运算符的形式及其功能
参数 作用 -r 若文件存在且用户可读,则测试条件为真 -w 若文件存在且用户可写,则测试条件为真 -x 若文件存在且用户可执行,则测试条件为真 -f 若文件存在且是普通文件,则测试条件为真 -d 若文件存在且是目录文件,则测试条件为真 -b 若文件存在且是块设备文件,则测试条件为真 -c 若文件存在且是字符设备文件,则测试条件为真 -s 若文件存在且文件长度大于0,则测试条件为真 -e 该是否存在 例如:
[root@ localhost ~]# test -w file1
执行后不会显示任结果,需要通过“$?”知道测试是否为真
[root@ localhost ~]# echo $?
还可以用下述方式获得测试结果:
[root@ localhost ~]# test -w file1 && echo "the file1 is writable"
或者:
[root@ localhost ~]# [ -w file1 ] [root@ localhost ~]# echo $?
字符串测试运算符的形式及其功能
参数 作用 -z s1 若字符串s1的长度为0,则测试条件为真 -n s1 若字符串s1的长度大于0,则测试条件为真 s1 = s2 若s1等于s2,则测试条件为真,“=”左右必须有空格 s1 != s2 若s1不等于s2,则测试条件为真 例如:
[root@ localhost ~]# [ -z $HOME ] [root@ localhost ~]# echo $?
需要注意的是:
[root@ localhost ~]# [ " $string1 " = " $string2 " ]
[ ]内每个组件都需要用空格分开;在字符串s1、s2比较时最好都用双引号括起来,否则可能会出现以下错误:
[root@ localhost ~]# name = "zhang san" [root@ localhost ~]# [ $name = "zhang san" ] bash: [ :too many arguments
上述例子会被解释成 zhang san = “zhang san”
数值测试运算符的形式及其功能
参数 作用 n1 -eq n2 若n1等于n2,则测试条件为真 n1 -ne n2 若n1不等于n2,则测试条件为真 n1 -lt n2 若n1小于n2,则测试条件为真 n1 -le n2 若n1小于或等于n2,则测试条件为真 n1 -gt n2 若n1大于n2,则测试条件为真 n1 -ge n2 若n1大于或等于n2,则测试条件为真 例如:
[root@ localhost ~]# number = 100 [root@ localhost ~]# [ " $number" -eq "100"] [root@ localhost ~]# echo $?
類
在前面shell基础曾写过一个命令:[root@ localhost ~]# ls /root/test && echo "yes" ||echo "no"
现在用脚本改写该命令如下:
#! /bin/bash echo -n "Please input a directory:" read dir if [ -d $dir ] then echo " $1 iis a directory " elif [ -f $dir ] echo "no" fi
命令的思路是判断前一条命令的”$?"的返回值是不是0,若是0,则前一条命令正确执行;若不是,则证明前一条命令执行错误。if的判断思路是测试条件判断式是否成立,若成立,则执行“then”中的命令;若不成立则执行“else”中的命令。
判断用户输入的数值是否在规定区间内,脚本如下:#! /bin/bash echo -n "Please input a data(1-10):" read a if [ "$a" -lt 1 ] || [ "$a" -gt 10 ] then echo "error number" exit 2 elif [ "$a" -lt 5 ] then echo " $1 is less 5" else echo " $1 is not less 5" fi
需要说明的是exit这条命令。这条命令是退出执行程序的命令,如果符号小于1或大于10的条件,则需要执行exit命令,exit后面的返回值赋予变量$?。
-
case
case语句只能判断一种条件关系
case的语法如下:case $变量名 in "值1" ) 命令 命令 ;; "值2" ) 命令 命令 ;; ...... * ) 命令 命令 ;; esac
" * “代表所有其他值,可以缺省
在每个分支程序之后要以” ;; "结尾,代表该程序结束
例子:#!/bin/bash echo -n "Please input your answer:" read answer case $answer in "yes" ) echo "Your choice is yes!" rm file ;; "no" ) echo "Your choice is no!" ;; * ) echo "Your choice is error!" ;; esac上述脚本请用户输入yes或no,若输入yes,则输出"Your choice is yes!",并删除相应文件;若输入no,则输出"Your choice is no!";若输入其他字符,则输出"Your choice is error!"



