一个例子学会shell脚本(第二章)

案例一:简易脚本安装jdk (暂时不是很完善)

#!/bin/bash


# 1.remove openjdk if exists.

for i in $(rpm -qa | grep jdk | grep -v grep)
do
 echo "deleteing rmp ->"$i
 sudo rpm -e $i  --nodeps
done

# 2.解压移动到具体的文件夹

java_dir=/usr/java99 #解压后复制到该目录下
java_tar=jdk-8u11-linux-x64.tar.gz #jdk默认放在cd目录下
java_name=jdk1.8.0_11 #解压后的文件名

rm -rf $java_dir/$java_name

mkdir -p $java_dir

echo "进入到默认目录:root用户是root"
cd 

tar -zxvf $java_tar

mv ./$java_name $java_dir/$java_name

rm -rf ./$java_name

# 3.处理环境变量

echo "export JAVA_HOME=${java_dir}/${java_name}">>/etc/profile
echo 'export PATH=$PATH:$JAVA_HOME/bin'>>/etc/profile #注意我这里没有用"

source /etc/profile

案例二、备份mysql数据  


username=用户名
password=密码

database1=库1名称
database2=库2名称

datetime=$(date +%Y%m%d_%H%M) #日期格式 20190405_1212
basedir=$(cd "$(dirname "$0")"; pwd)  #获取当前目录

echo 当前路径$basedir
echo 当前时间戳$datetime

basedir=$basedir/$(date +"%Y")/$datetime

mkdir -p $basedir 

echo 基础路径$basedir

back1=$database1-$datetime.sql #文件名称=库名称+时间.sql
back2=$database2-$datetime.sql

mysqldump -u$username -p$password $database1 > $basedir/$back1
mysqldump -u$username -p$password $database2 > $basedir/$back2

cd $basedir
cd ..

# 跳转到基础路径的上一层,进行压缩操作

zip -r ${datetime}.zip ${datetime}

if [ -e "${datetime}" ]
then
 rm -rf ${datetime}
fi;

案例三、 rpm 安装mysql5.7


arr=$(rpm -qa | grep mysql)

if [ -n "$arr" ] 
then 
  echo "存在原安装:是否删除(y/n)"
  if [ "$(read name)" == "y" ] 
  then 
     for v in $arr
     do 
     yum -y remove $v
     done 
  fi
else 
  echo "不存在原安装"
fi


echo "开始删除老版本的文件  (/etc/my.cnf , var/lib/mysql 不删除)"

rm -rf /usr/lib/mysql
rm -rf /usr/include/mysql

echo  开始安装依赖
yum -y install make gcc-c++ cmake bison-devel ncurses-devel libaio libaio-devel

echo 下载软件

#指定mysql的版本

version="5.7.13-1.el6.x86_64"

url="http://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-${version}.rpm-bundle.tar"

wget ${url}

#删除指定rpm版本,比如mariadb

removeRpm () {
 local list=$(rpm -qa|grep "$1")
 if [ -n $list ]
 then
   for i in $list
   do
     rmp -e $i   
   done
 fi
}

removeRpm mariadb


echo.跳转到当前文件的目录

cds=$(cd "$(dirname "$0")";pwd )

cd $cds

if [ -e "temp" ]
then
 rm -rf "temp"
fi

mkdir temp

cd temp

tar -xvf ../mysql-${version}.rpm-bundle.tar

rpm -ivh mysql-community-common-${version}.rpm
rpm -ivh mysql-community-libs-${version}.rpm
rpm -ivh mysql-community-client-${version}.rpm
rpm -ivh mysql-community-server-${version}.rpm

cd ..
rm -rf temp
rm -rf mysql-${version}.rpm-bundle.tar



 

你可能感兴趣的:(linux基础)