- shell的作用:
采集数据
对系统健康状况进行检测,不适合开发,效率过慢
语言分类:
描述性语言 (直接调用系统资源)
解释型语言 (在运行时,需要开启解释器)
企业中,shell一般用作单机,不做批量处理,效率太低 - 代码组成:逻辑(处理事件的合理方法)与数据
1.diff
-
用法:
num1,num2 ##第一个文件中的行
a ###添加
c ##更改
d ##删除
< ##第一个文件中的内容
> ##第二个文件中的内容
num3 num4 ##第二个文件中的行 -
diff lee westos ##比较两文件
-
常用参数
-b diff -b westos lee ##忽略空格
-B diff -B westos lee ##忽略空行
diff -bB westos lee ##同时忽略空行和空格
-i ##忽略大小写
diff -Bi westos lee ##同时忽略空行和大小写
-c ##显示文件所有内容并标示不同
diff -c westos lee
-r ##对比目录
diff -r lee1 westos
-u diff -u westos lee ##合并输出
2.patch ##需安装
- patch 原文件 补丁文件
patch westos file.path ##原文件消失
-b ##备份原文件
patch -b westos file.path
file.path lee westos westos.orig ##原文件 westos.rej
3.cut (指定列)
head (指定行)
- cut
-d : ##指定:为分隔符
-f ##指定显示的列 1-2 1到2列 1,3 1和3列 3- 3列之后 -3 到第三列
-c ##指定截取的字符 - cut -d I -f 1 westos ##指定I为分隔符截取第一列
cut -d I -f 3- westos ##3列以后
cut -d I -f -2 westos ##1~2列
cut -d I -f 1,3 westos ##1,3列
cut -d I -f 1-3 westos ##1-3列
cut -c 3- westos ##指定截取第三个字符以后的字符
4.sort
- -n ##纯数字排列
sort -n westos ##正序纯数字排序
-r ##倒叙
sort -nr westos ##逆序排序
-u ##去掉重复
sort -nu westos
-o ##输出到指定文件
sort -nu westos -o westos1 ##将排序输出至westos1中
-t ##指定分隔符
-k ##指定排序的列
sort -t 1 -k 2 -n westos ##以1为分隔符对第二列进行纯数字排序
5.uniq
- c ##合并重复并统计重复个数
sort -n westos | uniq -c ##统计每行出现的次数
-d ##显示重复的行
sort -n westos | uniq -d ##显示出现超过一次的行
-u ##显示唯一的行
sort -n westos | uniq -u ##显示只出现一次的行
- 仅输出IP地址
ifconfig | head -n 2 | tail -n 1 | cut -d ’ ’ -f 10
ifconfig ens160 | cut -d ’ ’ -f 10 | sed -n ‘2p’
6.tr (替换单个字符,字符串替换不理想)
- tr ‘a-z’‘A-Z’ ##小写转大写
tr ‘A-Z’ ‘a-z’ ##大写转小写
7.test (比较)
- 一般用[]代替
["$a" = “$b”] && echo yes ||echo no ##等于
["$a" != “$b”] && echo yes ||echo no ##不等于
["$a" -gt “$b”] && echo yes ||echo no ##大于等于
["$a" -ge “$b”] && echo yes ||echo no ##大于等于
["$a" -lt “$b”] && echo yes ||echo no ##小于
["$a" -le “$b”] && echo yes ||echo no ##小于等于
["$a" -eq “$b”] && echo yes ||echo no ##相等
["$a" -ne “$b”] && echo yes ||echo no ##不等于
[!"$a" -le “$b”] && echo yes ||echo no ##小于等于,内部条件为真,判定为假
and ##和,都为真为真
or ##或,一个为真为真
-n ##不为空
-z ##为空 - test关于文件的判定
-nt ##文件1是否比文件2新
-d ##是否目录
-L ##软连接
-e ##存在
-f ##普通文件
-b ##块设备 - c ##字符设备
-ef ##文件节点号是否一致
-ot ##文件1是否比文件2老
-S ##套接字
~/.vimrc
set ts=2 ai ##缩进两个空格 - 检测文件类型
1.检测存在性
2.检测类型
[ -z "\$*" ] && {
echo Error
exit
}
[ -e "\$*" ] || {
echo "\$*" is not exist
exit
}
[ -L "\$*" ] &&{
echo ""\$*" is link file"
exit
}
[ -f "\$*" ] &&{
echo ""\$*" is common file"
exit
}
[ -d "\$*" ] &&{
echo ""$*" is directory"
exit
}
8.&& ||
- 条件判断
&& ##条件成功动作
|| ##条件不成功动作
/dev/null
测试user1是否存在
vim check_user.sh
id user1 &> /dev/null &&{
echo user1 is exit!!
}||{
echo user1 is not exist
}
sh check_user.sh
id \$* &> /dev/null &&{
echo -e "\033[32m\$* is exit!!\033[0m"
}||{
echo -e "\033[31m $*is not exist\033[0m"
}
sh user_check.sh westos
31m : 红色
32m : 绿色
[ -z "$*" ] && {
echo error
}||{
id $* &> /dev/null &&{
echo $* is exit!!
}||{
echo $* is not exist
}
}