How to simply recreate copy/paste functionality like in gui environments?

My typical scenario for copying file/directory in Linux console is:

cp source_path target_path

Sometimes paths are relative, sometimes absolute, but I need to provide them both. It works, but there are situations where I would like to recreate scenario from gui which is:

1. go to source directory
2. copy file/directory
3. go to target directory
4. paste file/directory

I imagine something like

cd source_directory_path
copy_to_stash source_name
cd target_directory_path
paste_from_stash [optional_new_target_name]

I know that there is a xclip app, but a documentation says that it copies content of a file, not a file handle. Also, I can use $OLDPWD variable and expand it when I copy file, but this is not a solution without some cumbersome.

Is there some simple, general, keyboard only, not awkward to use equivalent? I don't want to use additional managers like ranger, midnight commander, only cli.


You should be able to do this with some basic functions, and the shell's $PWD variable to get the absolute path, to save a name you specify & later copy it wherever you happen to be. Here's two for bash (dash/sh might just require using test or [ instead of [[):

# source me with one of:
# source [file]
# . [file]

# Initialize

# Fuction to save a file in the current PWD
if [[ -e "$PWD/$1" ]]; then
    echo "Saved for later: $sa_file"
    echo "Error: file $PWD/$1 does not exist"

# Paste if file exists, to $1 if exists
if [[ -e "$sa_file" ]]; then
    if [[ $1 ]]; then
        cp -v "$sa_file" "$1"
        cp -v "$sa_file" .
    echo "Error: file $sa_file does not exist, could not copy"

I used the names sa for save, and pa for paste [since less typing = better right?] but naming them anything would work, like copy_to_stash.


You could use xclip to copy and paste the paths to files.

cd source_directory_path
realpath some_file | xclip  # Copy the path to a file
cd target_directory_path
cp "$(xclip -o)" .          # Copy ("paste") the file to the current directory

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.