if语句
1.if-then
if command
then
commands#command#退出状态码为0时执行
fi
2.if-then-else
if command
then
commands1#退出状态码为0时执行
else
commands2#退出状态码不为0时执行
fi
3.if-elif-else
if commanda
then
commands1#commanda退出状态码为零执行,且后续语句不再执行
elif commandb
then
comands2#commanda退出状态码不为0且commandb退出状态码为0时执行
elif commandc
then
commands3
else
commands4#abc的退出状态码均不为0时执行
fi
test
1.test condition
if test condition
then
commands
fi
使用test时若condition为空,则以非0状态码退出。执行else
2.test测试整数值
if [ condition ]#注意空格
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
3.test测试字符串
if [ condition ]
str1 = str2 检测str1是否和str2相同
str1 != str2 检测str1是否和str2不相同
str1 \< str2 检测str1是否比str2大#注意转义字符
str1 \> str2 检测str1是否比str2小#注意转义字符
-n str1 检测str1的长度是否非0
-z str1 检测str1的长度是否为0
4.test测试文件
if [ condition ]
-d file 检测file是否存在并且是一个目录
-e file 检测file是否存在
-f file 检测file是否存在并且是一个文件
-r file 检测file是否存在并可读
-w file 检测file是否存在并可写
-s file 检测file是否存在并非空
-x file 检测file是否存在并可写
-O file 检测file是否存在并属当前用户所有(大写)
-G file 检测file是否存在并默认组与当前用户相同
file1 -nt file2 检测file1是否比file2新
file1 -ot file2 检测file1是否比file2旧
5.复合测试
&&
|| #注意短路
if-then 高级特性
1.双括号
(( expression ))
expression可以为
val++ 后增
val-- 后减
++val 先增
--val 先减
! 逻辑求反
~ 位求反
** 幂运算
<< 左位移
<< 右位移
& 位布尔与
| 位布尔或
&& 逻辑与
|| 逻辑或
2.使用双方括号
[[ expression ]]
可以进行模式匹配
case命令
case $PWD in
/home/slowalker | $PWD )
echo slowalker;;
/home/benqie/ )
echo benqie;;
esac
1.if-then
if command
then
commands#command#退出状态码为0时执行
fi
2.if-then-else
if command
then
commands1#退出状态码为0时执行
else
commands2#退出状态码不为0时执行
fi
3.if-elif-else
if commanda
then
commands1#commanda退出状态码为零执行,且后续语句不再执行
elif commandb
then
comands2#commanda退出状态码不为0且commandb退出状态码为0时执行
elif commandc
then
commands3
else
commands4#abc的退出状态码均不为0时执行
fi
test
1.test condition
if test condition
then
commands
fi
使用test时若condition为空,则以非0状态码退出。执行else
2.test测试整数值
if [ condition ]#注意空格
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
3.test测试字符串
if [ condition ]
str1 = str2 检测str1是否和str2相同
str1 != str2 检测str1是否和str2不相同
str1 \< str2 检测str1是否比str2大#注意转义字符
str1 \> str2 检测str1是否比str2小#注意转义字符
-n str1 检测str1的长度是否非0
-z str1 检测str1的长度是否为0
4.test测试文件
if [ condition ]
-d file 检测file是否存在并且是一个目录
-e file 检测file是否存在
-f file 检测file是否存在并且是一个文件
-r file 检测file是否存在并可读
-w file 检测file是否存在并可写
-s file 检测file是否存在并非空
-x file 检测file是否存在并可写
-O file 检测file是否存在并属当前用户所有(大写)
-G file 检测file是否存在并默认组与当前用户相同
file1 -nt file2 检测file1是否比file2新
file1 -ot file2 检测file1是否比file2旧
5.复合测试
&&
|| #注意短路
if-then 高级特性
1.双括号
(( expression ))
expression可以为
val++ 后增
val-- 后减
++val 先增
--val 先减
! 逻辑求反
~ 位求反
** 幂运算
<< 左位移
<< 右位移
& 位布尔与
| 位布尔或
&& 逻辑与
|| 逻辑或
2.使用双方括号
[[ expression ]]
可以进行模式匹配
case命令
case $PWD in
/home/slowalker | $PWD )
echo slowalker;;
/home/benqie/ )
echo benqie;;
esac