一、shell中的基本知识
1.什么是shell
shell 也是操作系统中的一个软件,它包在 linux 内核的外面,为用户和内核之间的交互提供了一个接口,系统中的命令用 shell 去解释,shell 接收系统回应的输出并显示其到屏幕中,bash = GNU Bourne-Again Shell
2.什么是shell脚本
脚本是一种解释型语言,用 shell 脚本保存执行动作,用脚本判定命令的执行条件,用脚本来实现动作的批量执行。
二、shell中的应用
1.shell脚本的创建
vim /etc/virmc
测试:
vim create.sh ##文件名任意,只是为了测试
2.diff和patch
echo 123 456 > westos
echo 123 678 > westos1 ##生成两个不同的文件
diff westos westos1 ##比较两个文件不同
diff -u westos westos1 ##生成补丁
diff -u westos westos1 > westos.path ##生成补丁文件
[root@server Desktop]# yum install patch -y ##安装打补丁的工具
[root@server Desktop]# patch -b westos westos.path ##将补丁westos.path安装到westos上,-b表示保留源文件,会生成.orig文件
- 不同目录的比较
mkdir linux linux1
touch linux/123 linux1/345
diff -r linux linux1
3.截取命令cut的使用
cut 命令多用与字符截取
cut -d 指定分隔符
cut -f 1,7|1-7 指定截取的列
cut -c 1,4|1-4 指定截取的字符位置
cp /etc/passwd .
cut -d : -f 1 passwd ## :表示分隔符为:
cut -d : -f 1-3 passwd
cut -d : -c 1-6 passwd
编写脚本 ip_show.sh 来显示主机ip
或:
sh ip_show.sh
4.sort命令的使用---多用于字符排序
sort -n 纯数字排序
sort -r 倒序
sort -u 去掉重复数字
sort -o 输出到指定文件中
sort -t 指定分隔符
sort -k 指定要排序的列
vim westos
sort -t : -k 1 -n westos ###按westos中第1列排序
sort -t : -k 1 -n westos -o sort ###将排序结果放入file文件中
sort -n westos| uniq -c ###每行显示一次并统计重复次数
sort -n westos | uniq -d ###显示重复的行
sort -n westos | uniq -u ###显示唯一的行
编写脚本,找出/etc中最大的文件
vim find_big.sh
sh find_big.sh
4.test命令的使用
test 命令和 [] 等同
test "$A" == "$B" 等同 [ "$A" == "$B" ]
[ "$A" = "$B" ] ##$1
[ "$A" != "$B" ]
[ "$A" -eq "$B" ] ##等于
[ "$A" -ne "$B" ] ##不等于
[ "$A" -le "$B" ] ##小于等于
[ "$A" -lt "$B" ] ##小于
["$A" -ge "$B" ] ##大于等于
["$A" -gt "$B" ] ##大于
["$A" -ne "$B" -a "$A" -gt "$B" ] ##不等于且大于
["$A" -ne "$B" -o "$A" -gt "$B" ] ##不等于或大于
[ -z "$A" ] ##为空
[ -n "$A" ] ##不为空
["file1" -ef "file2" ] ##判断节点相不相等,ln 用ls -li查看节点
["file1" -nt "file2" ] ##file1日期早于file2
["file1" -ot "file2" ] ##file1日期晚于file2
编写脚本,若ip可以ping通,则显示 ip is up,ping不通显示 ip is down
vim check_ip.sh
ping /root/Desktop/check_ip.sh 172.25.254.68
ping /root/Desktop/check_ip.sh 172.25.254.1
编写脚本,判断数字是否在0~10
vim num_check.sh
[-e "file" ] ##文件是否存在
[-f "file" ] ##是否为普通文件
[-L "file" ] ##是否为连接
[-S "file" ] ##套结字 ,rsync -D /dev/vdb /mnt/file
[-b "file" ] ##块设备,rsync -D /var/lib/mysql/mysql.sock /mnt/file
[-d "file" ] ##目录
[-c "file" ] ##字符设备,rsync -D /dev/pts/1 /mnt/file
编写脚本,判断文件是否存在,若存在,判断它是什么类型的文件
[ -z "$1" ]&&{
echo "please input a file name after script!!!"
exit 1
}
[ -e "$1" ]||{
echo "$1 is not exist!!!"
exit 0
}
[ "-L" "$1" ]&&{
echo "$1 is a link"
exit 0
}
[ "-f" "$1" ]&&{
echo "$1 is a common file"
exit 0
}
[ "-b" "$1" ]&&{
echo "$1 is a block file"
exit 0
}
[ "-S" "$1" ]&&{
echo "$1 is a S file"
exit 0
}
[ "-d" "$1" ]&&{
echo "$1 is a dir "
exit 0
}||{
echo "$1 is a file"
}
编写脚本,实现大小写的转换
WORD=$(echo $1 | tr 'A-Z' ''a-z) ##大小写的自动转换
[ "$WORD" = "hello" ] && {
echo yes
} || {
echo no
}
编写脚本,创建用户,若用户存在则会提示
[ "$#" -eq "2" ]||{
echo "please input username and password after script!!!"
exit 1
}
Check_User=`getent passwd $1`
[ -n "$Check_User" ]&&{
echo "$1 is exist!!!"
exit 1
}||{
useradd $1
echo $2 | passwd --stdin $1
}