Last Updated: February 25, 2016
· derrylwc

Copy base64 version of file to your clipboard

Oftentimes we want to include files as a base-64'd data URI, rather than a path to the resource itself.

Build tools like Grunt can automate this process – but occasionally you'll want/need to process individual files.

My old workflow often involved converting the file online, or converting via command line and then manually removing the newline characters… so I decided to make it quick and painless.

The Bash Function

Just add this function to your .bashrc:

function b64() {
  cat $1 | base64 | pbcopy;

And now you can b64 filename in any directory, and its base64'd contents will be copied to your clipboard.



Nick Douma thoughtfully suggested that I use base64 instead of openssl, as it's more widely supported on *nix systems.

Previously the function looked like this…

function b64() {
  openssl base64 -in $1 | tr -d "\n" | pbcopy;

My openssl implementation also required that I strip newline characters from the output – however with base64 there is no such need.

4 Responses
Add your response


Why use this solution, which depends on OpenSSL, while base64 is a builtin command on many Unixes:

cat image.png | base64 -w0
over 1 year ago ·

My simple reply is... there's no good reason :-P

I've always used the openssl command. I wasn't aware that base64 was available as a standalone executable.

Thanks for sharing. I'll probably switch to this technique instead – as it's more terse and removes an extra step from the process.

over 1 year ago ·

By default there is no base64 installed on Mac machines. But python and OpenSSL is installed on almost every unix derivat.
So please keep it general with OpenSSL command.

over 1 year ago ·

It was available on mine – presumably by default, as I don't recall ever installing it. Feel free to use whichever version is supported by your system

over 1 year ago ·