My Digital Garden

pbcopy and pbpaste in WSL

pbcopy and pbpaste in WSL

pbcopy and pbpaste are commands available at the command line in MacOs that copy from STDIN to the clipboard and paste from the clipboard to STDIN respectively.

In WSL2 the functionality is missing, and the clipboard is the Windows clipboard, so you need to create a coupl;e of fake scripts to do the job.

Implementation

  1. create or find a folder under your userprofile that is in the PATH. For example:

    • create folder ~/bin

    • edit your ~/.profile to include:

        # set PATH so it includes user's private bin if it exists
        if [ -d "$HOME/bin" ] ; then
          PATH="$HOME/bin:$PATH"
        fi
  2. create a script pbcopy in that folder, add the following contents:

     #!/bin/bash
     # the pbcopy script
     tee <&0 | clip.exe
     exit 0
  3. create a script pbpaste in that folder, add the following contents:

     #!/bin/bash
     # the pbpaste script
     powershell.exe Get-Clipboard | sed 's/\r$//' | sed -z '$ s/\n$//'
     exit 0
  4. make both scripts executable

    chmod +x pbcopy
    chmod +x pbpaste

See also