Unix pipe to clipboard with WSL, and in UTF-8
WSL is good, it will be even better if we can pipe stdout directly into Windows host’s clipboard. Just like
1 ./myscript.sh | to-my-clipboard.sh
Note that xclip requires X, so it is not an option. From WSL, we have direct access to Windows executables. The easiest method would be using clip.exe:
1 ./myscript.sh | clip.exe
The method works fine if you don’t touch CJK characters or emojis. clip.exe didn’t handle the encoding well since the default codepage in Windows is not 65001(UTF-8). The command below would probably break
1 echo 😀 | clip.exe
The solution is to provide clip.exe with an environment in which the encoding can be specified. PowerShell is a natural fit for the job in Windows. We can do the trick with two simple steps:
- Setup PowerShell profile
The PowerShell profile is like
.bashrcbut for PowerShell. You may need to create a.ps1file in the location of$PROFILE.echo $PROFILEin PowerShell would give you the full path of the profile, something likeC:\Users\\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1. Ensure the path andnotepad.exe $PROFILElet you edit the file with notepad. Put the content in the file
1 chcp 65001 | Out-Null
- Use
clip.exewith PowerShell in WSL With the setup above, you may simply pipe the result of any command from WSL to your Windows.
1 # with powershell 5.1
2 echo 😀 | powershell.exe -Command clip.exe
3 # with powershell 7.x
4 echo 😀 | pwsh.exe -Command clip.exe
You can also wrap it in a bash script
1 echo 'pwsh.exe -Command clip.exe' > ~/.local/bin/clip.sh
2 chmod +x ~/.local/bin/clip.sh
Then you can write
1 echo 😀 | clip.sh
Note that, I have also looked into Set-Clipboard cmdlet in the PowerShell. But I never got to escape the content passing through WSL-PowerShell pipe right.