'Moving files between different WSL2 instances? [closed]

If it is possible, how can I move files from one WSL instance to another directly? This would be useful when trying out new distributions, e.g. for copying /home from Ubuntu 18.04 to 20.04.

I am weary of doing this through explorer by accessing \\wsl$ in the windows host, it doesn't seem to reliably transfer all the files and feels wrong overall.



Solution 1:[1]

How to share data between different WSL instances

1. Create shared directory which is not included in any WSL instances

mkdir /mnt/wsl/share

This will create /mnt/wsl/share directory shared across all WLS instances but not included in any WSL instances.

You can share data via this shared directory.

However, it is still impossible to directly copy/paste data between WSL instances.

(Note that the shared directory is automatically removed when rebooting.)

2. Create shared directory included in a WSL instance

You can make existing directory in WSL instance shared across other WSL instances by using bind mount.

For example, you have two WSL instances, Ubuntu-A and Ubuntu-B.

1. Open ~/.profile in Ubuntu-A and add below code.

# bind mount shared directory
if [ ! -d /mnt/wsl/share-a ]; then
  mkdir /mnt/wsl/share-a
  wsl.exe -d Ubuntu-A -u root mount --bind / /mnt/wsl/share-a/
fi

2. Open ~/.profile in Ubuntu-B and add below code.

# bind mount shared directory
if [ ! -d /mnt/wsl/share-b ]; then
  mkdir /mnt/wsl/share-b
  wsl.exe -d Ubuntu-B -u root mount --bind / /mnt/wsl/share-b/
fi

This will automatically mount the root directory (/) of Ubuntu-A to /mnt/wsl/shared-a/ and do the same thing for Ubuntu-B when you launch WSL.

https://jinsuxpark.blogspot.com/2021/01/how-to-share-data-between-different-wsl-instances-eng.html

Solution 2:[2]

On item 2, I put the following in my ~/.profile (well technically my .bash_profile).

if [[ -n "${WSL_DISTRO_NAME}" ]]; then
   if [[ -d "/mnt/wsl/${WSL_DISTRO_NAME}" ]]; then
      ls "/mnt/wsl/${WSL_DISTRO_NAME}"
   else 
      mkdir "/mnt/wsl/${WSL_DISTRO_NAME}"
      # note the terminating / on the directory name below!
      wsl.exe -d ${WSL_DISTRO_NAME} -u root mount --bind / "/mnt/wsl/${WSL_DISTRO_NAME}/"
   fi
fi

The result is every distro I start gets its root directory mounted with the "obvious" name.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jinsu Park
Solution 2 roachsinai