ct38 发表于 2018-8-28 07:22:06

Shell语法学习篇

  转义字符:

  在对文本解析时,双引号会对字符串解析,单引号保持字面含义。


  echo $?本bash最近一次进程退出码
  双引号用于保持引号内所有字符的字面值(回车也不例外),但以下情况除外:


  条件测试:退出码0表示成功,非0表示失败
  对于整形值言,
  -gt表示大于即great
  -ge表示大于等于great equal
  -eq表示相等equal
  -lt表示小于即little
  -le表示小于等于
  read val表示从标准输入读到val
  对于字符串比较:直接使用=,==(建议使用),或!=
  可选择$str1==$str2,或"X$str1"=="X$str2"(建议,防止$str1为空时直接比较,X为任意字符)
  此处不可使用单引号,单引号只取字面意思


  运行结果:


  运行结果:




  -d判断是否存在且是目录
  -f判断是否存在且是普通文件
  dir存在且是目录,test不存在,test.sh存在是普通文件

  比较字符串最好写成如下方式:


  if-elseif语句:分支







  $1是一个自动变量,脚本生成时创建:第一个参数,即test.sh.
  序列号容器:vector,数组下标从0开始
  关联号容器:脚本容器(map:以字符串作为下标)


















  转载:
  shell中[[]]与[]的区别?
  1.概念上来说
  "[[",是关键字,许多shell(如ash bsh)并不支持这种方式。ksh, bash(据说从2.02起引入对[[的支持)等支持。
  "["是一条命令, 与test等价,大多数shell都支持。在现代的大多数sh实现中,"["与"test"是内部(builtin)命令。
  2. 相同:二者都支持算术比较和字符串比较表达式(具体使用可能有点不同)
  (1)"-gt", "-lt"是算术比较操作符,用于比较整数的大小。
  (2)">", ""
  true
  2.2 “[[“用法
  $` 2 -gt 10 `&&echo true||echo false
  false
  $` 2 -lt 10 `&&echo true||echo false
  true
  仍然按字符串比较
  $[[ 2 < 10 ]]&&echo true||echo false
  false
  $[[ 2 > 10 ]]&&echo true||echo false
  true
  
  3.相同:都支持简单的模式匹配
  这里的模式匹配要简单得多,类似文件名的统配符的扩展规则。还要注意等号右端的模式不能用引号括起,使用引用关闭了某些元字符的特殊功能
  
  3.1“[“用法
  $ [ test = test ]&&echo true||echo false
  true
  $ [ test = t*t ]&&echo true||echo false
  true
  $ [ test = t..t ]&&echo true||echo false#not match.
  false
  $ [ test = "t??t" ]&&echo true||echo false #alert: don't quote the pattern,使用引用关闭了?的特殊功能
  false
  


  
  3.2“[[“用法
  $ [[ test = test ]]&&echo true||echo false#normal compare
  true
  $ [[ test = t*t ]]&&echo true||echo false#pattern match.
  true
  $ [[ test = t..t ]]&&echo true||echo false#not match.
  false
  $ [[ test = t??t ]]&&echo true||echo false
  true
  $ [[ test = "t??t" ]]&&echo true||echo false # alert: don't quote the pattern,使用引用关闭了?的特殊功能
  false
  


  4.不同点
  4.1逻辑与和逻辑或
  (1)"[" :逻辑与:"-a";逻辑或:"-o";
  (2)"[[":逻辑与:"&&";逻辑或:"||"
  $ [[ 1 < 2 && b > a ]]&&echo true||echo false
  true
  $ [[ 1 < 2 -a b > a ]]&&echo true||echo false
  bash: syntax error in conditional expression
  bash: syntax error near `-a'
  $ [ 1 < 2 -a b > a ]&&echo true||echo false
  true
  $ [ 1 < 2 && b > a ]&&echo true||echo false#wrong syntax
  bash: [: missing `]'
  false
  $ [ 1 < 2 \&\& b > a ]&&echo true||echo false#aslo wrong
  bash: [: &&: binary operator expected
  false
  


  
  4.2命令行参数
  (1)[ ... ]为shell命令,所以在其中的表达式应是它的命令行参数,所以串比较操作符">" 与"
页: [1]
查看完整版本: Shell语法学习篇