Linux Command Line and Shell Scripting Bible__第9章

第9章 使用结构化命令

---------------------------

 

  
    
# if -then
if command
then
command
fi

-------------------

# if-then-else
if command
then
command
else
command
fi

------------------

# elif
if command1
then
command
elif command2
then
more command
fi

-------------------

# more elif
if command1
then
command set
1
elif command2
then
command set
2
elif command3
then
command set
3
elif command4
then
command set
4
fi

 

 

 

 

  
    
# test condition

# ---------1-----------
if test condition
then
commands
fi

# ---------2-----------
if [ condtion ] # 中括号与条件之间必须有空格!
then
commands
fi

 

 

test数值比较:

 

  
    
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

 

 

 

test字符串比较

 

  
    
str1 = str2 str1与str2是否相同
str1
!= str2 str1与str2是否不同
str1
< str2 str1是否小于str2
str1
> str2 str1是否大于str2
- n str1 str1长度是否大于0
- z str1 str1长度是否为0

 

 

 

在test命令中,大写字母小于小写字母。

在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旧

 

复合条件检查

[ condition1 ] && [ condition2 ]    #两个条件都满足才执行then部分。

[ condition1 ] || [ condition2 ]    #任意一个条件评估为True,则执行then部分。

 

if-then的高级特

(( expression ))    # 双圆括号表示数学表达数。< 和 < 不必转义。

[[ expression ]]    # 双方括号表示高级字符串处理函数。

 

双圆括号命令符号

  
    
val ++ 后增量
val
-- 前减量
++ val 前增量
-- val 后减量

! 逻辑否定
~ 逐位取反
** 取幂

<< 逐位左移
>> 逐位右移
& 逐位布尔逻辑与
| 逐位布尔逻辑或
&& 逻辑与
|| 逻辑或

 

case命令

 

  
    
case variable in
pattern1
| pattern2) command1;;
pattern3) command2;;
* ) default command3;;
esac

 

 

 

 

你可能感兴趣的:(command)