云深处 发表于 2018-8-25 13:11:33

shell体验三

  shell 脚本的测试和比较
  test 命令:检查文件类型和比较数值的(根据表达式的执行结果(是真还是假),返回一个退出状态。)
  NAME
  test - check file types and compare values
  DESCRIPTION
  Exit with the status determined by EXPRESSION.
  ***************************************************************************************
  文件测试操作符:
  -d (directory) 文件存在且(&&)为目录,返回true
  -f (file) 文件存在且(&&)为普通文件,返回true
  -e(exit) 文件存在,返回true
  -r(read)文件存在可读,返回true
  -w(write)文件存在可写,返回false
  -x(executable)文件存在可执行,返回true
  -L (link)文件存在且为链接文件,返回true
  file1 -nt file2 (nt==>newer then),以文件的修改时间比较,文件file1 比file2的新,返回true
  file1 -ot file2 (ot==>older then),以文件的修改时间比较,文件file1比file2的旧,返回true
  查看文件的属性:可以通过ls和stat :例如:
  $ stat .bash_history
  File: `.bash_history'

  >  Device: 802h/2050d      Inode: 1049700   Links: 1
  Access: (0600/-rw-------)Uid: (500/ swallow)   Gid: (500/ swallow)
  Access: 2017-01-23 14:44:54.134193735 +0800
  Modify: 2017-01-23 05:43:16.301220988 +0800
  Change: 2017-01-23 05:43:16.301220988 +0800
  $ ls -l .bash_history
  -rw-------. 1 swallow swallow 18690 Jan 23 05:43 .bash_history
  举例测试:
  $ file1=del.sh ;file2=sum.sh
  $ echo $file1 $file2
  del.sh sum.sh
  $ ls -l $file1 $file2
  -rw-rw-r--. 1 swallow swallow 81 Jan 21 20:14 del.sh
  -rw-rw-r--. 1 swallow swallow 84 Jan 21 16:55 sum.sh
  $ test -f $file1 && echo 0 || echo 1(测试file1是否为普通文件。如果是返回0 不是返回1)
  0
  test 语法可以 简写为 []但是[] 在书写的时候要注意 [] 和内容之间要空格。
  $ [ -d $file2 ] && echo 0 || echo 1
  1
  $ [ $file1 -nt $file2 ] && echo 0 || echo 1
  0
  扩展:linux文件权限体系的两种表示方法。
  r: 代表可读    w:代表可写   x: 代表可执行 这个是权限的rwx 表示方法:
  与之对应的的数字表示方法: r: 4   w:2x:1   即 4+2+1=7(-:0没有权限为0)
  $ [ -x $file1 ] && echo 0 || echo 1
  1
  我们查看一个系统脚本来体验test的用法;
  $ cat /etc/init.d/nfs
  # Check for and source configuration file otherwise set defaults
  [ -f /etc/sysconfig/nfs ] && . /etc/sysconfig/nfs
  *****************************************************************************************
  字符串测试操作符;比较2个字符串是否相同,测试字符串的长度为0或为null(空字符串)
  -n "字符串"(nonzero) 字符串长度不为0 ,返回true。也就是说字符串要内容
  -z "字符串"(zero) 字符串长度为0,返回true。字符串为空或不存在。
  "字符串1" = "字符串2"   这里 = 可用 == 代替
  "字符串1" != "字符串2"   这里 = 可用 == 代替
  关注点: 1.这里比较字符串最好将字符串用""包裹。例如"file1"
  2. 如果判断相等的时候,= 前后空格。在计算机里面= 常被用来赋值(var=123)
  用一个不存的变量 var测试 -n-z
  $ echo $var
  $ [ -n "$var" ] && echo 0 || echo 1
  1
  $ [ -z "$var" ] && echo 0 || echo 1
  0
  ***************************************************************************************
  逻辑操作符:
  -a (and,与,两端都为真,结果为真) 也可以写成 &&
  -o (or,或,两端有一个是真,结果为真)也可以写成 ||
  !(not,非,两端相反。则结果为真)
  逻辑操作符是在上面单个判断的基础上来的 。需要结合单个判断的结果,进行组合判断。
  需要注意的是: -a -o多用于[]里面      && || 多用于[]之外
  *************************************************************************************
  整数的二元比较符
  -eq(equal) (== 或=)
  -ne (not equal) (!== 或!=)
  -gt(greater than) (>)
  -ge(greater equal)(>=)
  -lt(less than) (
页: [1]
查看完整版本: shell体验三