#!/bin/bash
echo '解压'
tar xf mysql-5.7.42-linux-glibc2.12-x86_64.tar.gz
echo '创建安装目录并将解压好的压缩包移动至该目录'
mkdir /app
mv mysql-5.7.42-linux-glibc2.12-x86_64 /app/mysql-5.7.42
ln -s /app/mysql-5.7.42 /app/mysql
sleep 1
echo '创建数据(data)目录'
mkdir /app/mysql/data
sleep 1
echo '创建mysql用户并授权'
user=$(cat /etc/group | grep 'mysql' | awk -F: '{print $1}')
if [ ! $user == mysql ];then
    groupadd mysql
    useradd -r -g mysql mysql
else
    echo "msyql用户已存在"
fi
chown -R mysql:mysql /app/mysql/
chmod 755 /app/mysql/
sleep 1
echo '安装依赖'
yum install -y libaio-devel >/dev/null 2>&1
sleep 1
echo '拷贝启动脚本'
cd /app/mysql/support-files
cp mysql.server /etc/init.d/mysqld
sleep 1
echo '初始化'
cd /app/mysql/bin/
output=$(./mysqld --initialize-insecure --user=mysql --datadir=/app/mysql/data --basedir=/app/mysql 2>&1 >/dev/null)

if [ $? -ne 0 ]; then
    echo "初始化失败,请检查环境"
        exit
else
    echo "初始化完成"
fi

echo '修改配置文件'
echo '
[mysqld]
basedir=/app/mysql
datadir=/app/mysql/data' > /etc/my.cnf
cat >> /usr/lib/systemd/system/mysql.service << EOF
[Unit]
Description=mysqld

[Service]
#Type=notify
ExecStart=/app/mysql/bin/mysqld --defaults-file=/etc/my.cnf --user=mysql
KillMode=process
Restart=on-failure
RestartSec=42s

[Install]
WantedBy=multi-user.target
EOF
#重新加载文件
systemctl daemon-reload
echo '添加环境变量'
sleep 1
echo 'PATH="/app/mysql/bin:$PATH"' > /etc/profile.d/mysql.sh
sleep 1
echo '请输入命令'source /etc/profile'加载环境变量'
`source /etc/profile`
systemctl start mysqld
sleep 1
echo '服务端口已启动'
netstat -tupln | grep '3306'
sleep 1
0