41 Comments

Command Line to Clipboard

Update: Script has been updated to add pipe support. Thanks to Nathan who allowed me to use his improvements.

It’s really something to be learning Linux. The more I learn about Linux the more I learn it’s about manipulating letters and numbers (well, this is more programming than anything but Linux is a lot about that). Bash I’m discovering is great; I’m just getting into it and now have made things a good deal easier by learning how to copy and paste text from the command line via the Xorg server clipboard. Here is a couple commands that can do it with examples, following them are a couple bash scripts that make this easy as can beasy.

The Programs

xsel and xclip are command line programs that can redirect the contents of the Xorg server clipboard. The Xorg server has two clipboards: the common right-click > Copy, and one for the middle-mouse click. For those that don’t know of it yet, the middle-click clipboard allows quick copy and pasting without having to enter a menu or using Ctrl + v. Anytime you select text on the Xorg server there is a separate register that records this text, then clicking the middle-mouse button (sometimes called the mouse button three [usually done by clicking down the scroll wheel] will paste the text. The Xorg server defines the the middle-click clipboard as primary and the right-click clipboard as secondary.

xclip

Here are the basics of using xclip. xclip, I prefer over xsel because I have found that xsel can have problems pasting to java apps.

xclip can be used in a variety of ways. First, for example, it can be piped to:

echo "hi" | xclip -selection clipboard

This will copy to the standard clipboard. For abbreviation, you can use c instead of clipboard. You can specify primary or p here too to copy to the middle-mouse button, but isn’t necessary as this is the default for xclip.

echo "hello" | xclip

To direct a file to xclip the -in or -out options are needed:

xclip -in -selection c <filename>
xclip -out -selection c <filename>

Which will respectively put a file into the clipboard, and write to a file from the clipboard contents.

To make the process quicker, I’ve created a couple scripts to automate the tasks called cb-in and cb-out and can be used like a standard command:

cb-in pack 
 File pack copied to the clipboard

cb-in

cb-out

xsel

To copy to the context-menu clipboard:

xsel --clipboard < /etc/fstab

To copy a text to the middle mouse button clipboard:

xsel < /etc/fstab

xsel can be piped too:

echo "a-bit-of-text" | xsel -b
cat /etc/make.conf | xsel -b

To output directly to the terminal:

xsel --clipboard

And to redirect and append to a file:

xsel --clipboard > Baada-Boom.txt
xsel --clipboard >> ~/.Baada-Boom

cp2clip (xsel)

#!/bin/bash
# cp2clip - copy to the clipboard the contents of a file

# Program name from it's filename
prog=${0##*/}

# Text color variables
bldblu='\e[1;34m'         # blue
bldred='\e[1;31m'         # red
bldwht='\e[1;37m'         # white
txtbld=$(tput bold)       # bold
txtund=$(tput sgr 0 1)    # underline
txtrst='\e[0m'            # text reset
info=${bldwht}*${txtrst}
pass=${bldblu}*${txtrst}
warn=${bldred}!${txtrst}

filename=$@

# Display usage if full argument isn't given
if [[ -z $filename ]]; then
    echo " $prog <filename> - copy a file to the clipboard"
    exit
fi

# Check that file exists
if [[ ! -f $filename ]]; then
  echo -e "$warn File ${txtund}$filename${txtrst} doesn't exist"
  exit
fi

# Check user is not root (root doesn't have access to user Xorg server)
if [[ $(whoami) == root ]]; then
  echo -e "$warn Must be regular user to copy a file to the clipboard"
  exit
fi

# Copy file to clipboard, give feedback
xsel --clipboard < "$filename"
echo -e "$pass ${txtund}"${filename##*/}"${txtrst} copied to clipboard"

clippaste (xsel)

#!/bin/bash
# clippaste - Paste contents of clipboard to file in terminal.
# use 'xclip -out -selection primary' for middle click clipboard

# Program name from it's filename
prog=${0##*/}

# Text color variables
bldblu='\e[1;34m'         # blue
bldred='\e[1;31m'         # red
bldwht='\e[1;37m'         # white
txtbld=$(tput bold)       # bold
txtund=$(tput sgr 0 1)    # underline
txtrst='\e[0m'            # text reset
info=${bldwht}*${txtrst}
pass=${bldblu}*${txtrst}
warn=${bldred}!${txtrst}

filename=$@
pasteinfo="clipboard contents"

# usage if argument isn't given
if [[ -z $filename ]]; then
  echo "clippaste <filename> - paste contents of context-menu clipboard to file"
  exit
fi

# check if file exists, prompt to append or override, else create new
if [[ -f $filename ]]; then
  echo -en "$warn File ${txtund}$filename${txtrst} already exists - (${txtbld}e${txtrst})xit, (${txtbld}a${txtrst})ppend, (${txtbld}o${txtrst})verwrite: "
  read edit
  case "$edit" in
    [aA] )  xsel --clipboard >> $filename
            echo -e "$pass File ${txtund}$filename${txtrst} appended with clipboard contents"
            ;;
    [oO] )  xsel --clipboard > $filename
            echo -e "$pass File ${txtund}$filename${txtrst} overwrote with clipboard contents"
            ;;
    * )     exit
    esac; else
    xsel --clipboard >> $filename
    echo -e "$pass File ${txtund}"$filename"${txtrst} created with clipboard contents"
fi
About these ads

About Gen2ly

<3's linux

41 comments on “Command Line to Clipboard

  1. Great to find out about xsel! Unfortunately two of you examples are wrong:
    echo “a-bit-of-text” | xsel -c
    cat /etc/make.conf | xsel -c
    do not copy “a-bit-of-text” or /etc/make.conf to the clipboard. They should be written:
    echo “a-bit-of-text” | xsel –clipboard
    cat /etc/make.conf | xsel –clipboard
    or, as I prefer, with the -b flag (equivalent to –clipboard, 8 characters shorter)
    echo “a-bit-of-text” | xsel -b
    cat /etc/make.conf | xsel -b

    The xsel -c flag does exist and is useful. It clears the clipboard. Forexample:
    xsel -c -b
    Or, if you want to clear the X Server clipboard (middle click clipboard), simply type
    xsel -c

    Enjoy!

  2. Huh, hmm that did work the last time I used it. Wonder if xsel option have changed since, looks like it does. Thanks for the tip Colin. I use xclip now so it’s a good time to update post.

  3. Awesome, thanks for the info

    I really need this to copy between the primary and the clipboard for apps which don’t know about the primary eg netbeans.

  4. Very nice Gen2ly, thanks for the idea!
    _______________________
    #!/bin/bash

    # Paste the contents of the clipboard to a file.

    FILENAME=$@

    if [[ ! -z $FILENAME ]]; then
    echo “clipb-pasted into $FILENAME “;
    xsel -b > $FILENAME;
    chmod 755 $FILENAME;
    else
    echo “no filenam declareted.”
    exit;
    fi

  5. This is awesome, thakns so much!

  6. […] phrase: bash copy to clipboard. Then start reading. Here is my favorite return on that search: http://linuxtidbits.wordpress.com/20…-to-clipboard/. But there others as […]

  7. !#/really/good/blog

    if
    i had to say one thing it’s
    thank you
    else
    i would not speak truly
    fi

  8. If you use xclip in conjunction with truecrypt you should be careful and use
    truecrypt .pass /media/pass
    cat /media/pass/password | xclip
    truecrypt -d .sec

    instead of
    xclip -in /media/pass/password

    because otherwise xclip will lock the file and you will get the following error message, when truecrypt tries to unmount the volume:
    umount: /media/pass: device is busy.

  9. […] http://linuxtidbits.wordpress.com/2008/02/22/command-line-to-clipboard/ GA_googleAddAttr("AdOpt", "1"); GA_googleAddAttr("Origin", "other"); GA_googleAddAttr("LangId", […]

  10. […] from the command line. I new it was possible and was pleasantly surprised to find a simple tutorial posted by Gen2ly on Linux Tidbits. Following his suggestion I used xclip to handle my clipboard. […]

  11. знакомства интим николаев знакомства в пензе секс русские секс знакомства знакомства для секса смоленск свингер знакомства знакомства для сексу знакомства для секса в щелково волгоград знакомства для секса знакомства для секса саранск http знакомства знакомства секс львов мобильные знакомства для секса подольск знакомства интим знакомства интим ташкент знакомства секс спб

    знакомства для сек знакомства секс великий новгород цель знакомства секс братск секс знакомства журнал знакомства

    дубна секс знакомства знакомства для секса киров знакомства яндекс г бузулук знакомства секс знакомства г уфа знакомства подольск секс идеал знакомства знакомства рязань ярмарка без регистрации интим знакомства знакомства без регистрации в белгороде

    знакомства для секса киев секс знакомства в тюмени ссекс знакомства знакомства для секса саратов секс знакомства мурманск

    винница секс знакомства трансексуалы знакомства знакомства для секса в крыму секс знакомства г уфа знакомства для секса саранск

  12. It help me much. Thank!

  13. Сетевые online and offline systems for gaming, arcade emulator, watch videos of programmy.http :/ / http://www.youtube.com/watch?v=n-fcO8eE_5I&noredirect=1

  14. Network online and offline systems for gaming, watching a video of programmy.http :/ / http://www.youtube.com/watch?v=n-fcO8eE_5I&noredirect=1

  15. Мы устанавливаем натяжные потолки в
    Серпухове не дорого, с гарантией!

  16. [url=http://shkatulka.net.ru/#k57x]Marlboro[/url] [url=http://psiport.ru/#eq7z]Cheap Cigarettes[/url] [url=http://news-royal.ru/vira-brezhnjeva-vzhe-znyala-obruchku/#ew7h]camel cigarettes[/url] [url=http://vegetables-fruited.ru/#kr1h]Buy Cigarettes Online[/url] [url=http://htmlshablons.ru/#d57h]Marlboro[/url] [url=http://pc-board.kiev.ua/compl/motherboards/40815.htm#eq1z]discount cigarettes[/url] [url=http://kif-belovodie.ru/#c36h]Camel Cigarettes[/url] [url=http://1mdk.ru/?p=55#bw1x]marlboro[/url] [url=http://resortbulgaria.ru/pages/turi-v-bolgariu/mejdunarodnii-molodejnii-tentr-cocteili-club.html#br7z]menthol cigarettes[/url] [url=http://motto5.ru/?page_id=126#eq1h][url=http://cigbase.com/[/url]

  17. [url=http://nikefreerunblackshoes.blogspot.com/]nike free run black[/url] As more and more people are turning to internet for marketing purpose, importance of article marketing cannot be overlooked It has emerged as one of the effective means of promoting any business You might have a question regarding how can article marketing can advertise any business and result into more sales There are numerous ways in which any website can benefit from article marketing The back links provided in your article helps in getting greater amount of traffic to your website [url=http://nikefreeshoesblue.blogspot.com/]nike free shoes[/url] That company must also be able to adjust its strategy in the event that search engine rankings drop Since search engine marketing is an on-going process, your positions must be constantly monitored If you want your search engine optimization company to do this for you, request a sample of a monthly report It is essential that this report should show rankings for the most popular search engines Don’t be impressed by a report that only shows great results for a limited number of small search engines http://nikefreerun3leathershoes.cabanova.com/.
    [url=http://cheapnikefreesale.blogspot.com/]cheap nike free[/url] If you bury your message inside a very thick and dense text, then you can very well lose the chance of getting a passerby or any of your target clients to get your message without having to work through your words If it is too much work to get to your message, then it is probably not worth to pick them up in the first placeGenerally, here are the guidelines you need to pick up yourself if you want your brochure printing copy to pique the interest of your target clients1 Speak directly to your target audience [url=http://nikefreesalecheap.weebly.com/]nike free sale[/url] Offloading the administrative work maximizes the organization’s resourcesOffer access to expertise Organizations that outsource gain access to know-how they probably do not possess They tap into a broad network of experienced people and best practicesThere are, however, some common misconceptions about outsourcing, including the belief that it can and will in every situation:Cut costs.

  18. Свисните где драйвер motherboard sony nw e002f драйвер загрузить
    И не нужно кривить свою модерскую харю xerox workcentre 3119 драйвер принтера драйвер на mini dv драйвер radeon 5800 драйвер для принтера brother dcp 7030r

  19. […] Command Line to Clipboard | Linux Tidbits – June 25th ( tags: clipboard xclip xsel linux cli ) […]

  20. This is the perfect site for everyone who really wants
    to understand this topic. You realize a whole lot its almost hard to argue with you (not that I personally would want to…HaHa).
    You definitely put a brand new spin on a topic which has
    been written about for many years. Wonderful stuff, just great!

  21. Vous desirez poser une ou des questions sur votre avenir ? notre cabinet pratique une vraie voyance par mail pour soulager
    vos interrogations.
    Quel que soit la question ou le domaine qui vous tient a coeur, notre cabinet repondra sans blabla ni detour pour vous apporter une reponse serieuse.

    http://www.expressvoyance.fr

    numerologie
    visit my site
    tarot gratuit
    c est gratuit

  22. It’s genuinely very complex in this busy life to listen news on TV, thus I only use web for that purpose, and obtain the most up-to-date news.

  23. Contraction de gollum et de élite, la gollumelite est une maladie assez rare, qui continue de faire en général le sommet de certaines pyramides mal concues, torturant le malade avec une sorte de déséquilibre shcyzophreniquo-égoiste couplé d’une sorte de syndrôme de la tourette… ” Mon précieux… butin passera avant tout mes principes ” ou ” maintenons les personnes dans l’ignorance pour leur vendre ce qui demeure gratuit ” sont le genre de phrasioles dégluties par les personnes en phase terminales de la maladie. Cette maladie pousse la victime à l’illusion de la réussite quand bien même en vérité c’est vers leffroyable echec qu’elle se précipite. La gollumelite developpe l’égo surdimentionnel et orgeuilleux des gens atteintes.

  24. Natural gas poses amazing some transportation problems and is mainly shipped through pipelines

  25. Many thanks, that’s nice, focused information.

  26. Вот фотки,в котором он сейчас состоянии: http://www.gansi.ru
    Видно, как он пытается перевернуться с помощью своей клешни.

  27. Hello Dear, are you truly visiting this web page daily, if so afterward
    you will without doubt obtain fastidious experience.

  28. Бесплатный сайт знакомств для секса.
    Знакомства онлайн с фото. Бесплатный видео чат.
    Частные фото и видео.

    http://www.bit.ly/1pm2xQj

  29. They are all equally important, so ensure you don`t miss any certainly one of them.
    The American researchers discovered that the tea contains polyphenols can kill the
    bacteria causing smelly breath.

    Experimental proof, drinking tea in vivo immune cell response to viruses is half a dozen times faster than drinking coffee.
    Thus, you’ll find countless homemade remedies to obtain rid of
    gnats, keeping your house clean and shielded from these tiny creatures.
    homepage

  30. If you’re operating over a dark road, generally there bollards will help
    for safety work in roadways and would make traveling safer
    and simpler to suit your needs. Most with the injuries happen from falls, particularly at home if elderly or disabled folks are living
    in there. news

  31. If you are going for best contents like me, only pay a quick visit this web page everyday because it presents feature contents, thanks

  32. What’s up to every body, it’s my first visit
    of this webpage; this weblog carries awesome and actually excellent data in favor of readers.

  33. Good thread, very useful, keep it up, thanks!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 52 other followers

%d bloggers like this: