#!/bin/bash
#配置数据库要安装的目录,可以根据自己的安装路径修改PATHDIR
PATHDIR="/project"
BASEDIR="$PATHDIR/mysql"
DATADIR="$BASEDIR/data"
#判断3306端口是否被占用
netstat -an | grep 3306 2>&1 > /dev/null
if [ $? -eq 0 ];then
echo -e "\033[5;31m 3306端口已经被使用... \033[0m"
exit 1
else
echo -e "\033[32m 准备安装...\033[0m"
fi
#创建mysql用户组和用户
groups mysql > /dev/null 2>&1
if [ $? -eq 0 ];then
echo "mysql用户组已经存在"
else
groupadd mysql
fi
id mysql >/dev/null 2>&1
if [ $? -eq 0 ];then
echo "mysql用户存在"
else
useradd -r -g mysql -s /bin/false mysql
fi
#备份mysql的配置文件 干部培训 http://www.cquyjy.com/
mv /etc/my.cnf /etc/my.cnf.backup >/dev/null 2>&1
cat >>/etc/my.cnf <<eof
[mysqld]
basedir=$BASEDIR
datadir=$DATADIR
eof
#解压mysql安装包
tar -xf mysql-5.7.26-linux-glibc2.12-x86_64.tar.gz -C $PATHDIR >/dev/null 2>&1
if [ $? -eq 0 ];then
echo -e "\033[32m 解压完成\033[0m"
else
echo -e "\033[31m 解压失败...\033[0m"
exit 1
fi
#移动解压包到安装目录下
mv $PATHDIR/mysql-5.7.26-linux-glibc2.12-x86_64 $BASEDIR >/dev/null 2>&1
#配置mysql环境变量
echo -e 'MYSQL=/project/mysql/bin\nexport PATH=$PATH:$MYSQL' >/etc/profile.d/mysql.sh
source /etc/profile.d/mysql.sh
if [ $? -eq 0 ];then
echo -e "\033[32m 环境变量配置成功,请稍等...\033[0m"
else
echo -e "\033[31m 环境变量配置失败...\033[0m"
exit 1
fi
#创建mysql的data目录
mkdir -pv $BASEDIR/data/
chown -R mysql:mysql $DATADIR
#初始化数据库,并将初始化结果存入tmp.txt文件中(初始化的密码在文件中,后面修改密码会用到)
mysqld --initialize --user=mysql --basedir=$BASEDIR --datadir=$DATADIR > $PATHDIR/tmp.txt 2>&1
#启动mysql服务,将mysql设置为systemd守护进程
cp $BASEDIR/support-files/mysql.server /etc/init.d/mysql
cat >/lib/systemd/system/mysql.service <<eof
[Unit]
Description=mysql
After=network.target
[Service]
Type=forking
ExecStart=/etc/init.d/mysql start
ExecReload=/etc/init.d/mysql restart
ExecStop=/etc/init.d/mysql stop
PrivateTmp=true
[Install]
WantedBy=multi-user.target
eof
echo -e "\033[32m 正在启动mysql服务,请稍等..\033[0m"
systemctl daemon-reload
systemctl start mysql.service
if [ $? -eq 0 ];then
echo -e "\033[32m mysql服务启动成功\033[0m"
else
echo -e "\033[5;31m mysql服务启动失败...\033[0m"
exit 1
fi
#请输入mysql修改的密码
read -p "初始化数据库mysql的密码,请输入您的数据库新密码:" PASSW
#修改mysql密码
cat tmp.txt|sed -n "$ p"|awk '{print $NF}'|xargs -i mysqladmin -uroot -h 127.0.0.1 -p"{}" password "$PASSW"
if [ $? -eq 0 ];then
echo -e "\033[5;32m 新密码设置成功,请妥善保管\033[0m"
else
echo -e "\033[5;31m 新密码设置失败\033[0m"
exit 1
fi