Linux学习笔记--结构化命令

来源:互联网 发布:macbook u盘接口知乎 编辑:程序博客网 时间:2024/06/07 11:18
一  if-then语句格式
     if  command
     then
         commands
     fi
    
  if-then-else语句格式
  if  command
  then
     commands
  else
    commands
  fi

嵌套if
if  command1
then
 commands
elif command2
then
  more commands
fi

二  test命令
  test的命令格式: test condition
如果condition成立,则test退出并返回状态码0,如果不成立退出,返回状态码1
if test condition
then
 commands
fi
另一种在if-then中使用test的方法
if [ condition ]
then
commands
fi
方括号定义了test命令用到的条件。condition和方括号之间要留有空格
test命令可以判断3类条件:数据比较,字符串比较和文件比较

三 数值比较
n1  -eq  n2            -------    检查n1是否与n2相等
n1  -ge   n2          -------    检查n1是否大于等于n2
n1  -gt  n2           -------    检查n1是否大于n2
n1  -le   n2          -------    检查n1是否小于等于n2
n1  -lt  n2          -------    检查n1是否小于n2
n1  -ne   n2        -------    检查n1是否不等于n2

四  字符串比较
str1 = str2       ----------  检查str1是否与str2相同      
str1 != str2    ----------  检查str1是否与str2不同     
str1 < str2     ----------  检查str1是否比str2小
str1 > str2    ----------  检查str1是否比str2大 
-n   str1       ----------  检查str1长度是否非0  
-z   str1      ----------  检查str1长度是否为0
需要注意的两个问题
1.大于小于符合必须转义,否则shell会把他们当成重定向符合而把字符串值当做文件名
2.大于小于顺序和sort命令所采用的不同

五 文件比较
-d   file    ------ 检查file是否存在且是一个目录
-e   file    ------ 检查file是否存
-f    file    ------ 检查file是否存在且是一个文件
-r   file     ------ 检查file是否存在且可读
-s    file    ------ 检查file是否存在且非空
-w    file    ------ 检查file是否存在且可写
-x     file    ------ 检查file是否存在且可执行
-O     file    ------ 检查file是否存在且属于当前用户所有
-G    file     ------ 检查file是否存在且默认组与当前用户相同
file1  -nt  file2    ------ 检查file1是否比file2新
file1  -ot  file2    ------ 检查file1是否比file2旧
 
六  符合条件测试
if -then 允许用布尔逻辑来组合测试
[ condition1 ] && [ condition2 ] 
[ condition1 ] || [ condition2 ] 

七  if-then高级特性
1.使用双圆括号(( expression )),expression 可以是任意的数学赋值或比较表达式,出来test命令使用的标准数学运算符,也可以用到以下运算符
val++
val--
++val
--val
!
~
**
<<
>>
&
|
&&
||

2.使用双方括号 [[ expression ]]

八  case 命令
    case命令格式

case variable in 
pattern1 | pattern2) commands1;;
pattern3) command2;;
*) default commands;;

case 命令会将指定的变量与不同的模式进行比较。如果变量和模式匹配,那么shell会执行为该模式指定的命令
































0 0
原创粉丝点击