Home > Net >  use ruby in WSL to copy text to clipboard
use ruby in WSL to copy text to clipboard

Time:11-18

on my Windows 10 machine I have an Ubuntu WSL installed with Ruby version 2.7.0. In my Ruby script I'm trying to take a value from a variable and copy it to the clipboard.

In looking into this I found out there isn't any real straight forward way to do this natively. I did find this SO post about a gem someone created to access the clipboard easily (here is the link to the github repo). I went through all the steps to install it and reference it in my gemfile, but the variable value is not getting copied to my clipboard for some reason.

Here's my code in my Ruby script:

puts data2

Clipboard.clear
Clipboard.copy(data2);p

at this point in my script the value I want to copy to the clipboard is in data2 and I verify the value is in there by putting it out to the console. I then try to clear the clipboard and then copy data2 to the clipboard as instructed in the github page. I run my script and it finishes but then when I try to paste the value that is on my clipboard it is not the value I am expecting (the value that is on my clipboard is the value that was on it before I ran my Ruby script).

Previously I had this working on a Mac using this code:

IO.popen('pbcopy', 'r ') { |clipboard| clipboard.puts data2 }

but this doesn't work on WSL because I believe pbcopy is a Mac OS thing.

One thing to note is that when I run my Ruby script it does give me this warning:

ruby: warning: shebang line ending with \r may cause problems

but I don't see how that would prevent the variable value from being saved to my clipboard.

Please can someone give me some insight into why this isn't working as expected, or even a different/better way of copying the variable value to my clipboard so I can paste the value after my Ruby script finishes running? As always a correct, clearly explained answer will be marked as accepted and upvoted.

Thanks!

CodePudding user response:

Thanks to @max for the insight. I was able to come up with a solution that does what I need it to, here's the code:

exec( "echo '#{data2}' | clip.exe" )

this code snippet takes the value stored inside data2 and copys it to the clipboard. When the script has finished running in my Ubuntu WSL, I can paste and the value on my clipboard is the value that was contained in data2 when the script was running.

Hope this helps anyone else with this question.

  • Related