How to use terminal to copy a file to the clipboard?

I got a file on desktop, file name is ded.html. To copy the file, I click the file and press cmd+c.

Now how would I do the same thing using terminal ?


Solution 1:

If I'm understanding the question right, what you're after is pbcopy and pbpaste.

Open a terminal and run:

cat ~/Desktop/ded.html | pbcopy

The file is now in your clipboard.

To put it somewhere else (i.e. paste it) run:

pbpaste > ~/Documents/ded.html

Now you should have a copy of ded.html sitting in ~/Documents.

Solution 2:

Lri’s answer is headed in the right direction, but it has a couple of flaws: there is no need to use Finder (the clipboard is part of the StandardAdditions OSAX), and giving a run handler is a much more reliable way to pass arguments from the command line (since 10.4). Making both of these changes greatly simplifies the “escaping” that needs to be done to enter the program in a shell.

Here is my version (wrapped in a shell function—you could put this in (e.g.) your .bashrc to make it available in your shells):

file-to-clipboard() {
    osascript \
        -e 'on run args' \
        -e 'set the clipboard to POSIX file (first item of args)' \
        -e end \
        "$@"
}

file-to-clipboard ~/Desktop/ded.html

A file that has been put on the clipboard with this script can then be pasted in Finder to copy the file to another folder.

osascript can also be used as a hash-bang interpreter (since 10.5). Put this in a file (e.g. file-to-clipboard)

#!/usr/bin/osascript
on run args
  set the clipboard to POSIX file (first item of args)
end

Make the file executable (chmod +x /path/to/where/ever/you/put/file-to-clipboard). Then run it like so:

/path/to/where/ever/you/put/file-to-clipboard ~/Desktop/ded.html

If it is stored in a directory in the PATH, then you can omit the path to the “script” file.