Search code examples
linuxbashshellclipboardxclip

Bash Script for Copying to Clipboard


My goal is to write an alias to copy the current command and its output to the clipboard, e.g.:

ls | myclip

This should result in the following being in the clipboard:

$ ls
Desktop Documents Downloads

Is this possible? So far, I tried:

myclip() {
    command="$@"
    output=$($@)
    echo -e "$command\n$output" | xclip -selection clipboard
}

This does not work, however.

Edit: This seems to somewhat work, however, for me it does not handle line breaks in the output correctly:

copyclip(){
    cmd=$(history 1 | sed 's/^ *[0-9]* *//' | sed 's/|.*//');
    output=$(cat);
    echo "\$ "$cmd$'\n'$output | xclip -sel clipboard;
    echo $output;
}

If anybody knows how to fix the line break issue, that would be great!


Solution

  • Working version:

    copyclip(){
        cmd=$(history 1 | sed 's/^ *[0-9]* *//' | sed 's/|.*//');
        output=$(cat);
        echo "\$ "$cmd$'\n'"$output" | xclip -sel clipboard;
        echo "$output";
    }