0 数字判断时使用符:
-gt 大于-lt 小于-ge 大于等于-le 小于等于-eq (用于数字) 或者 == 等等于(用于字母)-ne不等于if cat 1.txt >/dev/null 2>&1;thenecho okfi;&1-->是指/dev/null,重定向错误重定向都指向/dev/null无论什么输出都输入同一文件&>即可,&>/dev/null
1 shell中的逻辑判断
格式1:if 条件 ; then 语句; fi
#!/bin/bash##练习if语句##17-1-19 严龙a=5if [ $a -gt 1 ]thenecho "a>1"fi
格式2:if 条件; then 语句; else 语句; fi
#!/bin/bash##练习if语句##17-1-19 严龙a=5if [ $a -gt 10 ]thenecho "a>1"elseecho "b"fi
格式3:if …; then … ;elif …; then …; else …; fi
#!/bin/bash##练习if语句##17-1-19 严龙a=5if [ $a -gt 10 ]thenecho "a>1"elif [ $a -lt 5 ]thenecho "b"elseecho "c"fi
逻辑判断表达式:if [ $a -gt $b ]; if [ $a -lt 5 ]; if [ $b -eq 10 ]等 注意到处都是空格
可以使用 && || -o -a结合多个条件
#!/bin/bash##练习if语句##17-1-19 严龙a=5if [ $a -lt 10 ] && [ $a -gt 3 ]或者if [ $a -lt 10 -a $a -gt 3 ]then echo okfi
2 if 判断文件、目录属性
if [ -f file ]判断是否是普通文件,且存在
#!/bin/bashif [ -f /tmp/1.txt ]thenecho okelseecho "1.txt is not file"fi
if [ -d file ] 判断是否是目录,且存在
#!/bin/bashif [ -d /tmp/ ]thenecho okelseecho "/tmp is not directory"fi
if [ -e file ] 判断文件或目录是否存在
#!/bin/bashif [ -e /tmp/ ]thenecho okelseecho "/tmp is not directory"fi
if [ -r file ] 判断文件是否可读
#!/bin/bashif [ -r /tmp/1.txt ]thenecho okelseecho "1.txt not read"fi
if [ -w file ] 判断文件是否可写
#!/bin/bashif [ -w /tmp/1.txt ]thenecho okelseecho "1.txt not read"fi
if [ -x file ] 判断文件是否可执行
#!/bin/bashif [ -x /tmp/1.txt ]thenecho okelseecho "1.txt not x权限"fi
if [ -n “$m” ] 判断非空 非空执行then后面的语句
-z 判断是空 空的话就执行then后面的语句
#!/bin/bash##if [ -n ]的练习##17-1-19 严龙read -p "please input a number:" nm=`echo $n|sed 's#[0-9]##g'`if [ -n "$m" ]thenecho "The character you input is not a number,please retry."elseecho $nfi
if grep -q 用grep匹配做条件,-q只做匹配不会打印出来
#!/bin/bashif grep -q 'root:' /etc/passwdthenecho "root exist"elseecho "root not exist"fi
3 if 判断一些特殊用法
if [ -z $a ] 这个表示当变量a的值为空时会怎么样
if grep -q ‘123’ 1.txt; then 表示如果1.txt中含有’123’的行时会怎么样 if [ ! -e file ]; then 表示文件不存在时会怎么样 if [ ! -s file ] then 表示文件大小为0内容为空会怎么样 if (($a<1)); then …等同于 if [ $a -lt 1 ]; then… [ ] 中不能使用<,>,==,!=,>=,<=这样的符号
