Android and Linux

Monday, May 3, 2010

Paste in an Android terminal

I've always found it useful to be able to paste the clipboard contents in a terminal. I often find links in the Browser that I want to download with wget, but how to get the link into terminal without having to type it out?

My brief search for how clipboard content is stored yielded no results. It would be nice if it was stored in a file so we could grab the contents, but it's probably held in memory. At any rate, there is a workaround very similar to the workaround I used on the iPhone.

I went looking for some sort of clipboard helper app that does store the clipboard in a text file. The one I settled on is called Clipstore by benishouga and it stores the clipboard contents in a plain text file at /data/data/jp.benishouga.clipstore/files/clip.txt.

It is meant to keep a clipboard history of multiple items and it stores every entry on a single line. It replaces newlines with a "n" tag so even if you have 20 clipboard history items consisting of multiple lines, the most recent item will always be on top and it will all be on a single line. So the paste script can simply be:
#! /system/bin/sh
# Requires the app "Clipstore" by benishouga and app must be opened or allowed to
# run in the background in order to transfer system clipboard to app clipboard
sed 's/<n>/\n/g;q' /data/data/jp.benishouga.clipstore/files/clip.txt
I suggest not naming it "paste" to avoid any conflicts with the unix command of the same name. I named it "clip".

Copy "clip" to your clipboard with this QR code:

I may try to figure out a way to do a copy command soon, but it isn't usually as handy.

Update: Copying text is actually pretty easy using Clipstore. You just have to stick the text in the file at /data/data/jp.benishouga.clipstore/files/clip.txt, but to use it, you have to open Clipstore and select the text. This makes Clipstore put it in the system's clipboard and it can then be pasted in any app. Neither the copy or paste are perfect, but I don't know of a way to access the system clipboard directly. Neither command is needed very often, although they're lifesavers when they are, so having an extra step isn't really a problem.

Here's the copy script:
#! /system/bin/sh
# Requires the app "Clipstore" by benishouga and text must be
# selected in Clipstore to transfer it to the system clipboard
in=$(cat -)
lines=$(echo "$in" | wc -l)
if [ "$lines" = 1 ]
then sed -i "1i\\
$in" /data/data/jp.benishouga.clipstore/files/clip.txt
inn=$(echo "$in" | sed ':a;N;s/\n//g')
sed -i "1i\\
$inn" /data/data/jp.benishouga.clipstore/files/clip.txt

Copy the "copy" script to your clipboard with this QR code: