How to use difftool and mergetool on Windows 10 Ubuntu bash

Solution to this problem is simplified!

Thanks to the Windows 10 version 1903 update, accessing the Linux subsystem from Windows 10 is now possible. It is much more easier.

Just make sure that git config --global --list has these lines. That's all!

diff.tool=p4merge
merge.tool=p4merge
difftool.p4merge.cmd=/mnt/c/Program\ Files/Perforce/p4merge.exe "$(wslpath -aw $LOCAL)" "$(wslpath -aw $REMOTE)"
mergetool.p4merge.cmd=/mnt/c/Program\ Files/Perforce/p4merge.exe "$(wslpath -aw $BASE)" "$(wslpath -aw $LOCAL)" "$(wslpath -aw $REMOTE)" "$(wslpath -aw $MERGED)"
mergetool.p4merge.trustexitcode=false

Takeaways:

  • Linux subsystem now resides at \\wsl$\{distro name}\ path.
  • Which means you can access the tmp folder at \\wsl$\Ubuntu\tmp\. Even from the File Explorer!
  • wslpath -aw command does the heavy lifting for you.
  • The command now properly translates Linux relative /tmp/whatever path to a Windows 10 relative path.

Create file p4mergebash.sh and set $PATH:

mkdir -p ~/bin
touch ~/bin/p4mergebash.sh
chmod +x ~/bin/p4mergebash.sh
echo 'export PATH=$PATH:/mnt/c/Program\ Files/Perforce' >> ~/.bashrc
source ~/.bashrc

p4mergebash.sh content:

#!/bin/sh

LOCAL="$1"
REMOTE="$2"

case "$LOCAL"
in
    *)
    L=$(echo "C:/Users/<username>/AppData/Local/lxss/rootfs${LOCAL}" | sed 's,/,\\\\,g')
    ;;
esac

case "$REMOTE"
in
    *)
    R=$(echo `git rev-parse --show-toplevel`/"$REMOTE" | sed 's,/mnt/c/,C:/,g' | sed 's,/,\\\\,g')
    ;;
esac

echo "$L"
echo "$R"
p4merge.exe "$L" "$R"

Above script assumes your AppData and your git repo are on C: drive. Insert your username into the angle brackets (i.e. <username>).

Note: Ensure there are no CRLF's in p4mergebash.sh.

Then set git config:

git config --global diff.tool p4mergebash
git config --global difftool.p4mergebash.cmd '~/bin/p4mergebash.sh $LOCAL $REMOTE'
git config --global difftool.prompt false
  • how to make git difftool to always export absolute paths
  • https://askubuntu.com/questions/759880/where-is-the-ubuntu-file-system-root-directory-in-windows-nt-subsystem-and-vice
  • Replace forward slash with double backslash enclosed in double quotes
  • https://gist.github.com/rcapraro/aad8a8c3ad96fe563fce

For Beyond Compare 4, add these lines to your .gitconfig file:

[merge]
    tool = BeyondCompare4
    guitool = BeyondCompare4
[diff]
    guitool = beyondcompare4
[difftool "beyondcompare4"]
    cmd = /mnt/c/Program\\ Files/Beyond\\ Compare\\ 4/bcomp.exe "$(wslpath -aw $LOCAL)" "$(wslpath -aw $REMOTE)"
[mergetool "BeyondCompare4"]
    cmd = /mnt/c/Program\\ Files/Beyond\\ Compare\\ 4/bcomp.exe "$(wslpath -aw $LOCAL)" "$(wslpath -aw $REMOTE)" "$(wslpath -aw $BASE)" "$(wslpath -aw $MERGED)"