本文共 3601 字,大约阅读时间需要 12 分钟。
需使用双括号括起来
if 条件; then 语句;fi
#!/bin/bash
a=5if [ $a -gt 3 ]thenecho "ok"fi~ // []中,变量和括号及逻辑表达式间有空格if条件;then 语句1;else 语句2;fi
#!/bin/bash
a=5if [ $a -gt 3 ]thenecho "ok"elseecho "fault"fiif条件;then 语句1;elif 条件2;then 语句2;else 语句3;fi
#!/bin/bash
a=5if [ $a -lt 3 ]thenecho "a<3"elif [ $a -gt 6 ]thenecho "a>6"elseecho "nook"fi-x:判断是否有执行权限
#!/bin/bash
f="/tmp/test/123456"if [ -e $f ]thenecho "ok"elseecho "no"fi// 判断这个文件或目录是否存在,存在返回ok,不存在返回noif [ -z "$a" ]:表示当变量a的值为空时会怎样
if [ -n "$a" ]:表示当变量a的值不为空时会怎样
-n和-z,都不能作用在文件上。只能作用于变量。
-z和-n为相反的两个条件
#!/bin/bash
n=wc -l /tmp/test.txt
if [ $n -gt 20 ]thenecho 1elseecho 0fi// 在该脚本中无语法错误,只是我们预设/tmp/test.txt是存在的// 如果该文件不存在,该脚本执行的时候就会报错 [root@localhost shell]# sh file.sh
wc: /tmp/test.txt: 没有那个文件或目录if.sh: 第 3 行:[: -gt: 期待一元表达式// 所以,为了避免这种错误的发生,需要将脚本写的更加严谨
// 需要在执行“if [ $n -gt 20 ]”之前先确认文件“/tmp/test.txt”是否存在#!/bin/bash
n=wc -l /tmp/test.txt
if [ -z $n ]thenecho "error"exit// 如果文件不存在执行到这里将会推出脚本// 下面的将不在执行elif [ $n -lt 20 ]thenecho 1elseecho 0fi 执行结果:
[root@localhost shell]# sh if.sh wc: /tmp/test.txt: 没有那个文件或目录errorif grep '123' test.txt;then 表示当test.txt中含有123会怎样
判断某参数不存在
#!/bin/bashif grep -wq 'user1' /etc/passwdthenecho "user1 exist."fi[root@localhost sbin]# sh if1.sh判断某参数不存在:
#!/bin/bashif ! grep -wq 'user1' /etc/passwdthenecho "no user1"fi// -w:精准匹配,过滤一个单词
// -q:安静模式,不打印过滤结果// !:取反grep 非安静模式:
[root@localhost shell]# ./file.sh user1:x:1005:1006::/home/user1:/bin/bashuser1 exist.grep 安静模式:
[root@localhost shell]# ./file.sh user1 exist.case语句为多选语句,可以用case语句匹配一个值与一个模式,如果匹配成功,执行相匹配的命令。
case 值($变量名) in
value1)command;;value2)command;;value3)command;;*)command;;esaccase 的工作方式如上所示,取值后面必须加in,每一个模式必须以有括号结束。取值将检测匹配的每一个模式。一但模式匹配,则执行完匹配模式相应命令后不再继续其他模式。
如果没有匹配到任何一个模式,则执行*模式后的命令。
在case中,可以在条件中使用|,表示或的意思
2|3)
command;;实例
#!/bin/bash
read -p "please input a number:" nif [ -z "$n" ]thenecho "null,please input a number."exit 1// exit 1 表示执行该部分命令后的返回值// 即,命令执行完后使用echo $? 的值fin1=echo $n | sed 's/[0-9]//g'
if [ $n -lt 60 ] && [ $n -ge 0 ]
thentag=1elif [ $n -ge 60 ] && [ $n -lt 80 ]thentag=2elif [ $n -ge 80 ] && [ $n -lt 90 ]thentag=3elif [ $n -ge 90 ] && [ $n -lt 100 ]thentag=4elsetag=0fi// tag是变量名,作为一个标签,方便引用。case $tag in1)echo "D";;2)echo "C";;3)echo "B";;4)echo "A";;*)echo "the number is range 0-100";;esaccase $tag in
1)echo "D";;2)echo "C";;3)echo "B";;4)echo "A";;*)echo "the number is range 0-100";;esac// 该脚本作用是输入考试成绩,判断考试成绩的等级
测试
[root@localhost shell]# ./case.sh
please input a number:95A[root@localhost shell]# ./case.sh please input a number:85B[root@localhost shell]# ./case.sh please input a number:75C[root@localhost shell]# ./case.sh please input a number:55D[root@localhost shell]# ./case.sh please input a number:101 the number is range 0-100[root@localhost shell]# ./case.sh please input a number:7yZM,please input a number.[root@localhost shell]# ./case.sh please input a number:null,please input a number.转载于:https://blog.51cto.com/754599082/2070006