Shell 脚本一键编译并且安装 mysql
2020-06-13 本文已影响0人
Renew全栈工程师
先新建文件
vim ./install-mysql.sh
1.不多说,上代码
#!/bin/bash
userName="mysql"
userGroup="mysql"
version=$1
if [ -z "$version" ]; then
version="5.7.30"
fi
getVersionMain(){
string=$1
array=(${string//./ })
unset array[2]
versionM=""
for var in "${array[@]}"; do
if [ -z "$versionM" ]; then
versionM="$var"
else
versionM+=".$var"
fi
done
echo "$versionM"
}
versionMax=$(getVersionMain "$version")
installDir="$2"
if [ -z "$installDir" ]; then
installDir="/usr/local/mysql"
fi
dataDir="$3"
if [ -z "$dataDir" ]; then
dataDir="/data/mysql"
fi
fileName="mysql-$version.tar.gz"
if ! wget -O "$fileName" "https://cdn.mysql.com//Downloads/MySQL-$versionMax/mysql-$version-linux-glibc2.12-x86_64.tar.gz"; then
echo "wget download mysql-$version fail"
exit 1
fi
if [ ! -f "$fileName" ]; then
echo "$fileName not found"
exit 1
fi
if ! tar -zxvf "$fileName"; then
echo "decompression fail"
exit 1
fi
mv "mysql-$version-linux-glibc2.12-x86_64" "$installDir"
groupadd "$userGroup"
useradd -r -g "$userGroup" "$userName"
mkdir -p "$dataDir"
chown mysql:mysql -R "$dataDir"
echo "[mysqld]
bind-address=0.0.0.0
port=3306
user=mysql
basedir=$installDir #这是刚才重命名的目录
datadir=$dataDir #这是刚才建立的数据存放目录
socket=/tmp/mysql.sock
log-error=$dataDir/mysql.err
pid-file=$dataDir/mysql.pid
#character config
character_set_server=utf8mb4
symbolic-links=0
explicit_defaults_for_timestamp=true" >>/etc/my.cnf
ln -s "$installDir"/bin/* /usr/bin
mysqld --defaults-file=/etc/my.cnf --basedir="$installDir" --datadir="$dataDir" --user=mysql --initialize
psword=$(cat "$dataDir/mysql.err" | grep 'root@localhost:')
cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysql
/etc/init.d/mysq start
echo "数据库初始化密码为:$psword"
2.命令
chmod +x ./install-mysql.sh
./install-mysql.sh
#./install-mysql.sh 5.7.30 /usr/local/mysql /data/mysql
#./install-mysql.sh 版本 安装路径 数据存放目录
3.修改默认密码
执行上面代码安装完毕后会输出密码
#如果没有输出则用下面密码进行查看
cat /data/mysql/mysql.err | grep 'root@localhost:'
#.... for root@localhost: s2dHVkYb1j+% ....其中 s2dHVkYb1j+% 就是密码
登录mysql
mysql -u root -p
#依次输入下面命令,然后重新登录
SET PASSWORD = PASSWORD('123456');
ALTER USER 'root'@'localhost' PASSWORD EXPIRE NEVER;
FLUSH PRIVILEGES;