jxdiscuz 发表于 2018-8-17 10:01:20

Unix Shell脚本编程知识点总结及范例


[*]  test命令可以处理shell脚本中的各类工作,它产生的不是一般输出,而是可使用退出状态,test接受各种不同的参数,可控制它要执行哪一种测试
[*]  语法:
[*]  test [ expression ]
[*]  test [ ]
[*]  用途:
[*]  为了测试shell脚本里的条件,通过退出状态返回其结果。
[*]  行为模式:
[*]  test用来测试文件的属性、比较字符串、比较数字
[*]  主要选项与表达式:
[*]  string      string不是null
[*]  -b file   file是块设备文件(-b)
[*]  -c file   file是字符设备文件(-c)
[*]  -d file   file为目录(-d)
[*]  -e file   file是否存在
[*]  -f file   file是一般文件(-)
[*]  -g file   file有设置它的setgid位
[*]  -h file   file是一个符号链接
[*]  -r file   file是可读的
[*]  -s file   file是socket
[*]  -w file   file是可写的
[*]  -x file   file是可执行的,或file是可被查找的目录
[*]  s1 = s2   s1与s2字符串相同
[*]  s1 != s2    s1与s2字符串不相同
[*]  n1 -eq n2   整数n1与n2相等
[*]  n1 -ne n2   整数n1与n2不相等
[*]  n1 -lt n2   整数n1小于n2
[*]  n1 -gt n2   整数n1大于n2
[*]  n1 -le n2   整数n1小于或等于n2
[*]  n1 -ge n2   整数n1大于或等于n2
[*]  -n string   string是非null
[*]  -z string   string为null特殊参数变量
[*]  在bash shell中有些特殊变量,它们会记录命令行参数的个数。例如$#
[*]  你可以只数一下命令行中输入了多少个参数,而不同测试每个参数。bash为此提供了一个特殊的变量,就是上面所提到的$#
[*]  $#的说明

[*]  $#特殊变量含有脚本运行时就有的命令行参数的个数。你可以在脚本中任何地方来调用这个特殊变量来调用$#来计算参数的个数

[*]  范例:

[*]  vim Count.sh
  #!/bin/bash
  #Script Name: Count.sh
  # Count Parameters number
  echo There were $# parameters.
  chmod +x Count.sh
  ./Count.sh 1 2 3
  There were 3 parameters.

  下面来说下${!#}的作用?
  既然$#变量含有参数的总数量,那么${!#}可以调用最后一个参数的变量名称。
  范例:
  vim Count-1.sh
  #!/bin/bash
  #Script Name: Count-1.sh
  # Print last parameter
  params=$#
  echo "The last parameter is "$params"
  echo "The last parameter is "${!#}"
  :wq
  chmod +x Count-1.sh
  ./Count-1.sh1 2 3
  The last parameter is 3
  The last parameter is 3


页: [1]
查看完整版本: Unix Shell脚本编程知识点总结及范例