MySQL - Relocate data directory using symbolic link

By xngo on April 27, 2019

In MySQL, there are multiple ways to relocate your data directory to another path. The easiest way I found is to use symbolic link. Here is the script that I wrote to relocate MySQL data directory to another path using symbolic link. The main idea is to create a symbolic link to /var/lib/mysql/ directory.

How to use ln-dir.sh script below:

# Stop MySQL service.
service mysql stop
 
# WARNING: /var/lib/mysql will be deleted.
./ln-dir.sh "/var/lib/mysql" "/your/new/dir/path/"
 
# Restart MySQL service.
service mysql start

ln-dir.sh

#!/bin/bash
set -e
# Description: Relocate directory using symbolic link.
script_name=$(basename "${0}")
 
from_dir=$1
to_dir=$2
 
# Error handling.
    cmd_eg=$(printf "%s\n%s\n" \
                "   e.g. ./${script_name} from_dir          to_dir" \
                "   e.g. ./${script_name} /var/lib/mysql/  /to/target/dir/"  \
            )
 
    # Stop if $from_dir is already a symbolic link.
    link_path=$(dirname "${from_dir}")
    link_name=$(basename "${from_dir}")
    (
        cd "${link_path}"
        if [ -L "${link_name}" ]; then
            echo "Error: ${from_dir} is already a symbolic link. Aborted!"
            echo "${cmd_eg}"
            exit 1;
        fi
    )
 
    if [ ! -d "${from_dir}" ]; then
        echo "Error: ${from_dir} is not a directory. Aborted!"
        echo "${cmd_eg}"
        exit 1;
    fi
    from_dir=$(readlink -ev "${from_dir}")
 
    if [ -z "${to_dir}" ]; then
        echo "Error: to_dir can't be empty. Aborted!"
        echo "${cmd_eg}"
        exit 1;
    fi
 
# Copy default files if $to_dir doesn't exist or is empty.
    if [ ! -d "${to_dir}" ]; then
        mkdir -p "${to_dir}"
        to_dir=$(readlink -ev "${to_dir}")
 
        # Copy all files in default directory, to new one, retaining perms (-p)
        cp -apv "${from_dir}"/*   "${to_dir}"
    fi
 
    if [ -z "$(ls -A ${to_dir})" ]; then
        mkdir -p "${to_dir}"
        to_dir=$(readlink -ev "${to_dir}")
 
        # Copy all files in default directory, to new one, retaining perms (-p)
        cp -apv "${from_dir}"/*   "${to_dir}"
    fi
 
# Set the same ownership & permission as $from_dir.
    # Set ownership of new directory to match existing one
    chown --reference="${from_dir}" "${to_dir}"
 
    # Set permissions on new directory to match existing one
    chmod --reference="${from_dir}" "${to_dir}"
 
# Create symbolic link.
    rm -rf "${from_dir}"
    ln -s "${to_dir}" "${from_dir}"
    ls -al "${from_dir}" 

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.