Copy and paste a file/directory from command line

command linecopy/pastefile-copy

Instead of using the following command:

cp {source file} {dest file}

I want to be able to copy a file into the clipboard, and paste it somewhere else, in another directory. something like this:

/usr/local/dir1# cp {source file}
/usr/local/dir1# cd /usr/local/dir2
/usr/local/dir2# paste

Is it possible?

Best Answer

I think you should do something like the GUI applications do. My idea for doing this is to write two functions for Copy and Paste, where Copy writes path of files to be copied to a temporary file and Paste reads those paths and simply calls cp command. My implementation (to be put in .bashrc file) is like below:

function Copy {
    touch ~/.clipfiles
    for i in "$@"; do
      if [[ $i != /* ]]; then i=$PWD/$i; fi
      i=${i//\\/\\\\}; i=${i//$'\n'/$'\\\n'}
      printf '%s\n' "$i"
    done >> ~/.clipfiles
}

function Paste {
    while IFS= read src; do
      cp -Rdp "$src" .
    done < ~/.clipfiles
    rm ~/.clipfiles
}

Better scripts could be written for implementing this idea, I tested my own and it works very well for files and folders (I don't know how xclip could work for copying folders!!)


For example:

/usr/local/dir1# Copy a.txt *.cpp
/usr/local/dir1# cd /usr/local/dir2
/usr/local/dir2# Paste

/usr/local/dir1# Copy *.h *.cpp b.txt subdir1
/usr/local/dir1# cd /usr/local/dir2
/usr/local/dir2# Paste

/usr/local/dir1# Copy a.txt b.txt 
/usr/local/dir1# cd /usr/local/dir2
/usr/local/dir2# Copy c.txt d.txt
/usr/local/dir2# cd /usr/local/dir3
/usr/local/dir3# Paste
Related Question