Shell笔记

Shell笔记

        • shell文件
        • 关键字
        • if 条件语句
        • 备份mysql
        • LAMP一键安装软件的脚本
        • for循环
        • while循环
        • Until循环语句
        • Case/Select 选择语句
        • 数组/函数编程
        • awk,sed,find,grep四剑客
        • 系统完整备份与增量备份
          • tar

shell文件

  • 文件.sh 结尾 :vim first.sh
  • ! bin/bash shell: 运行环境
  • chomd +x :shell文件执行权限

关键字

  • echo:打印输出
  • sh xxx.sh 123 abc :123第一个参数,间隔空格输入第二个参数
  • echo $1:打印输入第一个参数
  • echo $?:判断上一句输入正确为“0”,比如如sql语法
  • echo $*:打印输入所有
  • echo $#:
  • echo -e ’ 033[32m----------\033[0m’ :\033[32m \033[0m 打印中间得文字输出颜色

if 条件语句

Shell笔记_第1张图片

  • -z :判断输入参数是否为空
  • -d :判断目录是否存在
  • -f :判断文件是否存在
  • -p 继承
  • -n: 脚本是否正确 /bin/bash -n xx.sh
  • 创建目录
  • Shell笔记_第2张图片

备份mysql

#! bin/bash/
# auto bakcup mysql db
# by authors l 2019
# define backup path
BAK_DIR=/data/backup/'date +%Y%m%d'
MYSQLDB=discuz
MYSQLUSER=backup
MYSQLPW=123456
MYSQLCMD=/user/bin/mysqldump

if [! -d $UID -ne 0]:then
	echo "Must to be use root for exec Shell."
	
if [! -d $BAK_DIR ];then
	mkdir -p $BAK_DIR
	echo -e "\033[32mThe $BAK_DIR] Create Successfully!"
else
	echo "This $BAK_DIR is exist..."
fi

$MYSQLCMD -u$MYSQLUSER -p$MYSQLPW -d $MYSQLDB >$BAK_DIR/MYSQLDB.sql
if [$? -eq 0];then
	echo -e "\0333[32mThe Mysql Backup $MYSQLDB Successfully033\0m"
	
else
	echo -e "\033[32mThe Mysql Backup $MYSQLDB Failed,Please check033\0m"
fi
  • 验证sh -n xx.sh
  • 授权user :grant all on cacti.* to backu@‘localhost’ identified by “123456”;
  • 定时执行/任务计划
    • crontab -e
    • 0 0 * * * /bin/bash /xx.sh >> /tmp/mysql_back.log

LAMP一键安装软件的脚本

#! /bin/bash
#auto make install LAMP
#by authors wugk 2014

#Httpd define path variable
H_FILES=httpd-2.2.27.tar.bz2
H_FILES_DIR=httpd-2.2.27
H_URL=http://mirrors.cnnic.cn/apache/httpd/
H_PREFIX=/usr/local/apache2/

if [ -z "$1"];then
	echo -e "\033[36mPlease Select Install Menu follow:\033[0m"
	echo -e "\033[32m1)编译安装Apache服务器\033[1m"
	echo  "2)编译安装MySQL服务器"
	echo  "3)编译安装PHP服务器"
	echo  "4)配置index.PHP并启动LAMP服务"
	echo  -e "\033[31mUsage:{ /bin/sh $0 1|2|3|4|help}\033[0m"
fi

# if第一个命令下载解压到指定目录
if ["$1" -eq "1"];then
	wget -c $H_URL/$H_FILES &&tar -jxvf $H_FILES &&cd $H_FILES_DIR ;./configure --prefix=$H_PREFIX
fi
	if [ $? -eq 0];then
		make &&make install
		echo -e "\033[32mThe $H_FILES_DIR Server Install Successfull!033[0m"
	else
		echo -e "\033[32mThe $H_FILES_DIR Server Install Failed, Please check!\033[0m"
		exit
	fi
	

  • wget -c M U R L / M_URL/ MURL/M_FILES &&tar -xzvf $M_FILES &&cd KaTeX parse error: Expected 'EOF', got '&' at position 13: M_FILES_DIR &̲&yum install cm…M_PREFIX \

for循环

# ! /bin/bash
j=0
for ((i=1 i<=100; i++))
do
   j='expr $1 + $j '
done
echo $j

#常用的
#找到所有文件打包
for i in 'find . -maxdepth /var/log -name "*.log"' | tail -2
do 
   tar -czvf $i.tgz $i
done

#tar xzf all.taz -C test02/ :-C 解压到指定目录

#远程主机批量传输文件
#ssh keygen——>远程免密钥
#将公钥拷贝到某台服务器,第一次用密码和,第二次只要authorized_keys里面有某台主机公钥就不需要输密码
覆盖:scp -r id_rsa.pub root@192.168.1.184:/root/.ssh/authorized_keys
追加:ssh-copy-id -i /root/.ssh/id_rsa.pub 192.168.1.184
#

while循环

  • read -p :打印变量信息
  • read line:逐行读取内容
while read line 
do
	echo $line
done </etc/hosts

# 循环ip列表执行命令
#!/bin/bash
# 远程拷贝到不同服务器
while read line
do
IP='echo $line |awk 'print $2''
	echo -e "\033[32mscp -r /tmp/test.txt root@$IP:/tmp \033[0m"
done <list.txt

Until循环语句

  • 知道满足条件,才退出,否则执行action
#!/bin/bash
#打印a<0直到条件满足
a=10
until [[$a -lt 0]];do
echo $a
((a--))
done

Case/Select 选择语句

#!/bin/bash
Ps3="selelct your will exec Menu"
#这个值要和case里面值匹配
select i in "apache" "Mysql"
do
case $i in
	apache)
	echo "Wait install httpd server....."
	tar jxvf httpd-2.2.27.tar.bz2;cd httpd-2.2.27
	;;
	Mysql)
	echo "Wait install Mysql server..."
	;;
esac
done #等待

数组/函数编程

Shell笔记_第3张图片
Shell笔记_第4张图片
Shell笔记_第5张图片

awk,sed,find,grep四剑客

  • vi内部修改:%s/old/new/g

  • sed外面修改:sed -i 's/old/new/g' test.txt

    • 行首添加空格(^:start,$:end): sed 's/^/& /g ' ,末尾添加空格sed 's/$/& /g'
    • 下一行添加(a:之后,i:之前):sed '/wgk/a test007/' test.txt
    • 打印行:(1p,第一行,1,5p:1至5行):sed -n '/wgk/p' test
    • 比对找最大最小数字cat num.txt | sed 's/ /\n/g' | grep -v '^$' | sort -nr | sed '1p;$p'(解:sed ‘s/ /\n/g’: 将所有空格换成换行符,grep -v ‘^$’:匹配开始到结束,sort -nr:降序,sed ‘1p;$p’:打印第一个和最后一个)
  • grep:匹配,grep -v:反义匹配

    • 例:grep '45':匹配45,grep -v '45':匹配除45的所有数据
    • 以什么开头:grep ‘^10’ test.txt
    • 以数字开头:grep ‘[0-9]’ test.txt
    • 以字母开头:grep "^[a-z]|[A-Z]" test.txt
    • 打印文件有多少IP:cat test.txt | grep -E '([0-9]{1,3}\.){3}[0-9]{1,3}'
    • -n:打印行号
    • 深入匹配:egrep ‘11|wgk’ test.txt
  • awk切割打印:

    • 打印某一列:awk '{print $1}'
    • 打印第一列(-F:以冒号切割,冒号可换成任何符号):cat test.txt | awk -F: '{print $1}'
    • awk括号添加注解:cat test.txt | awk '{print 'echo; ' $NF}'
  • Find:查找

    • 从更目录查找文件:find / -name 'test.txt'
    • 当前第一级目录(-maxdepth:指定查找深度, -type f:类型文件,-mtime +30多少天以前,-mtime -1,一天前,-exec rm -rf {} \:承接命令,承接之前的引入到大括号中进行删除):find . -maxdepth 1 -type f -name 'test.txt' -mtime +30 -exec rm -rf {} \
    • 移动大于50M的文件:find . -maxdepth 1 -size +50 -type f -exec mv {} /tmp/ \;

系统完整备份与增量备份

tar
  • 全备份:tar -g /tmp/snapshot -czvf /tmp/xx.tar.gz /data/sh/
  • 增量备份:tar -g /tmp/snapshot -czvf /tmp/xxadd.tar.gz /data/sh/
  • 查看备份信息:cat /tmp/snapshot
  • 先还原完整的,在还原增量的
  • 写一个每周日全备份,其余天增量备份
#例:年:date+%y
#!/bin/bash/
#auto backup linux system files
SOURCE_DIR={
	$* #所有
}
TARGET_DIR=/data/backup/
YEAR='data +%Y'
MONTH='data +%m'
DAY='data +%d'
WEEK='data +%u'
A_NAME='data +%H%M'
FILES=${A_NAME}_SYSTEM+backup.tgz
CODE=$? #检查前面命令执行正确
if [ -z "$*"];then
	echo -e "\033[32mUsage:\nPlease Enter Your Backup Files or Dircetories\n------------------------\n\nUsage; { $0 /boot /etc}\033[0m"
	exit
fi

#Determine whether the Target Directory Exists
if [-d $TARGET_DIR/$YEAR/$MONTH/$DAY ];then
	mkdir -p  $TARGET_DIR/$YEAR/$MONTH/$DAY
	echo -e "\033[32mThe $TARGET_DIR Create Successfully !\033[0m"
fi

#EXEC Full_Backup Function Command
Full_Backup(){
if [ "$WEEK" -eq "7" ];then
	rm -rf $TARGET_DIR/snapshot
	cd $TARGET_DIR/$YEAR/$MONTH/$DAY ;tar -g $TARGET_DIR/snapshot -czvf $FILES ${SOURCE_DIR[@]}
	[ "CODE" == "0"]&&echo -e "---------------------\n\033[32mThese Full_Backup System Backup Successfully !\033[0m"
fi
}

#Perform incremental BACKUP Function Command
Add_Backup(){
if [ $WEEK -ne "7" ];then
	cd $TARGET_DIR/$YEAR/$MONTH/$DAY ;tar -g $	TARGET_DIR/snapshot -czvf $A_NAME$FILES ${SOURCE_DIR[@]}
	[ "$CODE" == "0" ]&&echo -e "----------------------\n\033[32mThese Add_Backup System Files $TARGET_DIR/$YEAR/$MONTH/$DAY/${YEAR}_$A_NAME$FILES Backup Successfully\033[0m"
fi
}

sleep 3
Full_Backup;Add_Backup

你可能感兴趣的:(Shell笔记)