/usr/bin/base64 – copying and pasting code / patches betweeen terminals

The Scenario

A couple of terminals open, connected to a mix of your own workstation, local development servers and remote servers running on a different network and frequently behind a variety of security barriers.

You want to copy a smallish chunk of code from a file across the network, or the output of a diff to apply a patch – but characters like whitespace and newlines which should not change will frequently be modified through the copy. You end up with whitespace changes where you don’t want them (perhaps later causing source code control merges to fail, and patches will fail straight away).

base64 / base64 -d to the rescue

Use /usr/bin/base64 to make sure the data you copy between terminals remains unchanged.

For example – call base64 on a file to give you a safe-to-copy chunk of ASCII:

$ base64 example001
aGVsbG8gd29ybGQK

Which you can then get back with “base64 -d”:

$ echo aGVsbG8gd29ybGQK | base64 -d
hello world

Or you can just transfer a patch, for example:

$ cat example001
hello world
$ cat example002
hello all
$ diff -u example001 example002 
--- example001  2016-08-09 16:20:52.383813529 +1000
+++ example002  2016-08-09 16:21:08.675813172 +1000
@@ -1 +1 @@
-hello world
+hello all
$ diff -u example001 example002 | base64 
LS0tIGV4YW1wbGUwMDEJMjAxNi0wOC0wOSAxNjoyMDo1Mi4zODM4MTM1MjkgKzEwMDAKKysrIGV4
YW1wbGUwMDIJMjAxNi0wOC0wOSAxNjoyMTowOC42NzU4MTMxNzIgKzEwMDAKQEAgLTEgKzEgQEAK
LWhlbGxvIHdvcmxkCitoZWxsbyBhbGwK

# And then in another terminal...
$ cat | base64 -d | patch
LS0tIGV4YW1wbGUwMDEJMjAxNi0wOC0wOSAxNjoyMDo1Mi4zODM4MTM1MjkgKzEwMDAKKysrIGV4
YW1wbGUwMDIJMjAxNi0wOC0wOSAxNjoyMTowOC42NzU4MTMxNzIgKzEwMDAKQEAgLTEgKzEgQEAK
LWhlbGxvIHdvcmxkCitoZWxsbyBhbGwK
patching file example001
$ cat example001 
hello all

So long as the text is relatively small this allows you to safely transfer exactly the data you intended between terminals.

In a text editor like vi you can even just copy the base64 encoded data into the file you are editing, and then pipe the range including that base64 data through “base64 -d” to get the code chunk you need right where you need it.

Leave a Reply

Your email address will not be published. Required fields are marked *