shell里的判断结构及注意事项

背景:早些时候shell里的判断结构写起来总是感觉不顺手,下边是一些注意事项,及用法介绍

判断的两种方式
"test"、"[]"
如下
test -f "$filename" 

[ -f "$filename" ]


使用中括号必须要特别注意,因为中括号用在很多地方,包括通配符与正则等等,所以如果要在 bash 的语法当中使用中括号作为 shell 的判断式时,必须要注意中括号的两端需要有空格符来分隔, 如下:


注意

1. 在中括号 [] 内的每个组件都需要有空格键来分隔; ps: “等号赋值”两边不能有空格
2. 在中括号内的变数,最好都以“”引起来,字符串变量一定要用“”
3. 在中括号内的常数,最好都以单引号括号起来。

附shell里的判断符号用法
判断字符串
-z string                   若string长度为0,则为真
-n string                   若string长度不为0,则为真
string1 == string2   相等
string1 != string2     不相等
判断数值
int1 -eq int2      等于
int1 -ne int2      不等于
int1 -lt int2        小于
int1 -le int2       小于
int1 -gt int2       大于
int1 -ge int2      大于等于
判断文件
-b filename  若文件存在且是一个块特殊文件,则为真
-c filename  若文件存在且是一个字符特殊文件,则为真
-d filename   若文件存在且是一个目录,则为真
-e filename   若文件存在,则为真
-f filename   若文件存在且是一个规则文件,则为真
-g filename  若文件存在且设置了SGID位的值,则为真
-h filename  若文件存在且为一个符合链接,则为真
-k filename  若文件存在且设置了"sticky"位的值
-p filename  若文件存在且为一已命名管道,则为真
-r filename   若文件存在且可读,则为真
-s filename   若文件存在且其大小大于零,则为真
-u filename   若文件存在且设置了SUID位,则为真
-w filename  若文件存在且可写,则为真
-x filename   若文件存在且可执行,则为真
-o filename   若文件存在且被有效用户ID所拥有,则为真
特殊变量
$# ----传递给程序的总的参数数目
$? ----上一个代码或者shell程序在shell中退出的情况,如果正常退出则返回0,反之为非0值。
$* ----传递给程序的所有参数组成的字符串。
$n ----表示第几个参数,$1 表示第一个参数,$2 表示第二个参数 ...
$0 ----当前程序的名称
$@----以"参数1" "参数2" ... 形式保存所有参数
$$ ----本程序的(进程ID号)PID
$! ----上一个命令的PID 

猜你喜欢

转载自blog.csdn.net/qq_34485930/article/details/80550104