pbcopy for Windows?

In MacOSX there's a command which can pipe the output of a command to the clipboard so that it can be pasted somewhere else in the GUI.

How can this be done from cmd.exe or with a PowerShell cmdlet?

6 Answers

Use something like:

someCommand | clip

That will pipe the result to the windows clipboard

6

I'm using the Git Bash command shell for Windows, and as someone noted above, using clip is very annoying, because it also copies the carriage return at the end of the output of any command. So I wrote this function to address it:

function cpy {
while read data; do # reads data piped in to cpy echo "$data" | cat > /dev/clipboard # echos the data and writes that to /dev/clipboard
done
tr -d '\n' < /dev/clipboard > /dev/clipboard # removes new lines from the clipboard
}

So for example:

$ pwd | cpy # copies directory path
$ git branch | cpy # copies current branch of git repo to clipboard
1

Just for reference I had to copy my public key directly after Bitbucket was giving me a bad key warning. I was able to use @soandos answer like so:

cat ~/.ssh/id_rsa.pub | clip to copy my key directly from the command line on a PC. (since command line sucks compared to terminal)

In PowerShell, just pipe the text into Set-Clipboard. For fast typing, you can use the alias scb. This doesn't add an extra line break like the clip utility does.

For example, this command puts the contents of myfile.txt on the clipboard:

gc .\myfile.txt | scb

Note that for objects that represent file system objects, Set-Clipboard will copy the object in the same sense that Explorer does when you Ctrl+C a file. If that's not what you wanted, pipe the object through Out-String first.

1

This function replaces the standard Windows clip in Git Bash where a trailing newline is copied.

function clip { printf "$(</dev/stdin)" | cat > /dev/clipboard
}

This is based on Matthew's answer which only preserves the last line and introduces a trailing newline. Using printf avoids the newline that echo adds.

For use in WSL/bash. Add to ~/.bashrc:

function pbcopy() { printf $(</dev/stdin) | clip.exe
}
export -f pbcopy
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like