0 数字判断时使用符:

  1. -gt 大于
  2. -lt 小于
  3. -ge 大于等于
  4. -le 小于等于
  5. -eq (用于数字) 或者 == 等等于(用于字母)
  6. -ne不等于
  7. if cat 1.txt >/dev/null 2>&1;
  8. then
  9. echo ok
  10. fi;
  11. &1-->是指/dev/null,
  12. 重定向错误重定向都指向/dev/null
  13. 无论什么输出都输入同一文件&>即可,&>/dev/null

1 shell中的逻辑判断


格式1:if 条件 ; then 语句; fi

  1. #!/bin/bash
  2. ##练习if语句
  3. ##17-1-19 严龙
  4. a=5
  5. if [ $a -gt 1 ]
  6. then
  7. echo "a>1"
  8. fi

格式2:if 条件; then 语句; else 语句; fi

  1. #!/bin/bash
  2. ##练习if语句
  3. ##17-1-19 严龙
  4. a=5
  5. if [ $a -gt 10 ]
  6. then
  7. echo "a>1"
  8. else
  9. echo "b"
  10. fi

格式3:if …; then … ;elif …; then …; else …; fi

  1. #!/bin/bash
  2. ##练习if语句
  3. ##17-1-19 严龙
  4. a=5
  5. if [ $a -gt 10 ]
  6. then
  7. echo "a>1"
  8. elif [ $a -lt 5 ]
  9. then
  10. echo "b"
  11. else
  12. echo "c"
  13. fi

逻辑判断表达式:if [ $a -gt $b ]; if [ $a -lt 5 ]; if [ $b -eq 10 ]等 注意到处都是空格

可以使用 && || -o -a结合多个条件

  1. #!/bin/bash
  2. ##练习if语句
  3. ##17-1-19 严龙
  4. a=5
  5. if [ $a -lt 10 ] && [ $a -gt 3 ]
  6. 或者
  7. if [ $a -lt 10 -a $a -gt 3 ]
  8. then echo ok
  9. fi

2 if 判断文件、目录属性


if [ -f file ]判断是否是普通文件,且存在

  1. #!/bin/bash
  2. if [ -f /tmp/1.txt ]
  3. then
  4. echo ok
  5. else
  6. echo "1.txt is not file"
  7. fi

if [ -d file ] 判断是否是目录,且存在

  1. #!/bin/bash
  2. if [ -d /tmp/ ]
  3. then
  4. echo ok
  5. else
  6. echo "/tmp is not directory"
  7. fi

if [ -e file ] 判断文件或目录是否存在

  1. #!/bin/bash
  2. if [ -e /tmp/ ]
  3. then
  4. echo ok
  5. else
  6. echo "/tmp is not directory"
  7. fi

if [ -r file ] 判断文件是否可读

  1. #!/bin/bash
  2. if [ -r /tmp/1.txt ]
  3. then
  4. echo ok
  5. else
  6. echo "1.txt not read"
  7. fi

if [ -w file ] 判断文件是否可写

  1. #!/bin/bash
  2. if [ -w /tmp/1.txt ]
  3. then
  4. echo ok
  5. else
  6. echo "1.txt not read"
  7. fi

if [ -x file ] 判断文件是否可执行

  1. #!/bin/bash
  2. if [ -x /tmp/1.txt ]
  3. then
  4. echo ok
  5. else
  6. echo "1.txt not x权限"
  7. fi

if [ -n “$m” ] 判断非空 非空执行then后面的语句

-z 判断是空 空的话就执行then后面的语句

  1. #!/bin/bash
  2. ##if [ -n ]的练习
  3. ##17-1-19 严龙
  4. read -p "please input a number:" n
  5. m=`echo $n|sed 's#[0-9]##g'`
  6. if [ -n "$m" ]
  7. then
  8. echo "The character you input is not a number,please retry."
  9. else
  10. echo $n
  11. fi

if grep -q 用grep匹配做条件,-q只做匹配不会打印出来

  1. #!/bin/bash
  2. if grep -q 'root:' /etc/passwd
  3. then
  4. echo "root exist"
  5. else
  6. echo "root not exist"
  7. 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… [ ] 中不能使用<,>,==,!=,>=,<=这样的符号