Unit tests run few times faster if I setup mysql instance in RAM memory, but because this is manual process, it take me some time to do this, and I need to do this on few server.
New mysql instance should run on port 3307, if it is free, otherwise return error.
So, first thing I need is to check if some service is already listen on this port, I added code for this, but on some servers it doesn’t show process that run on 3307 port, even if there are such processes. I need help to improve this script. I don’t have much experience with shell programming.
#!/bin/bash
STAT=`netstat -na | grep 3308 | awk '{print $6}'`
if [ "$STAT" = "LISTEN" ];
then
echo "There is already process that listen on port 3307"
fi
# Create ramdisk
mkdir -p /mnt/ramdisk
mount -t tmpfs -o size=1G tmpfs /mnt/ramdisk
chown mysql:mysql /mnt/ramdisk
port=3307
distribution=$(lsb_release -i | cut -f2)
if [ $distribution == 'Debian' ]
then
mkdir /var/lib/mysql2
chown -R mysql.mysql /var/lib/mysql2/
mkdir /var/log/mysql2
chown -R mysql.mysql /var/log/mysql2
cp -R /etc/mysql/ /etc/mysql2
cd /etc/mysql2/
sed -i "s/3306/$port/g" my.cnf
sed -i "s/mysqld.sock/mysqld2.sock/g" my.cnf
sed -i "s/mysqld.pid/mysqld2.pid/g" my.cnf
sed -i "s/var\/lib\/mysql/var\/lib\/mysql2/g" my.cnf
sed -i "s/var\/log\/mysql/var\/log\/mysql2/g" my.cnf
mysql_install_db --user=mysql --datadir=/mnt/ramdisk
mysqld_safe --defaults-file=/etc/mysql2/my.cnf &
elif [ $distribution == 'CentOS' ]
then
cp /etc/my.cnf /etc/my2.cnf
cd /etc
sed -i "s/3306/$port/g" my2.cnf
sed -i "s/mysqld.sock/mysqld2.sock/g" my2.cnf
sed -i "s/mysqld.pid/mysqld2.pid/g" my2.cnf
sed -i "s/var\/lib\/mysql/var\/lib\/mysql2/g" my2.cnf
sed -i "s/var\/log\/mysql/var\/log\/mysql2/g" my2.cnf
mysql_install_db --user=mysql --datadir=/mnt/ramdisk
mysqld_safe --defaults-file=/etc/my2.cnf &
else
exit 13
fi
Ignoring the fact that you used 3308 in your test, to check if something is listening on a port, you might instead want to use netcat, which simply tries to connect:
You could similarly use
lsof -i TCP:"$port" -s TCP:LISTENwhich would have the perhaps desirable side effect of printing the listening command if there is one. The advantage of nc/lsof over parsing netstat is that you can’t parse it wrong (your case would break if an app listened to UDP port 13307 for example).You may want to add
set -eas the second line. This will make bash abort if one of the commands fail (e.g. due to missing files or permissions), instead of pointlessly continuing with the next commands and potentially ruining something.You can also use multiple expressions in one sed command, and use different delimiters for s to avoid excessive escaping:
Just in general, you may also want to
sed -i '1i# Autogenerated file, do not edit' my.cnfto add a comment on the first line, so people won’t modify it and have their changes overwritten.