Encode or Decode base64 from terminal

There are many random times working with api’s, mail servers, or other random tasks in a Linux terminal or ssh session that you run into the need to pass data encoded with base64 or decode a response that is encoded. At first look, this seems like a bit a of pain, but it doesn’t have to be. 

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.

Each base64 digit represents exactly 6 bits of data. Three 8-bit bytes (i.e., a total of 24 bits) can therefore be represented by four 6-bit base64 digits.


There are numerous websites that offer to do this for you, but if you are concerned about your data and privacy, it might be worthwhile to avoid them and deal with it on your own.

The command to encode and decode base64 text is an easy one to remember:



$ base64 --help
Usage: base64 [OPTION]... [FILE]
Base64 encode or decode FILE, or standard input, to standard output.

With no FILE, or when FILE is -, read standard input.

Mandatory arguments to long options are mandatory for short options too.
-d, --decode decode data
-i, --ignore-garbage when decoding, ignore non-alphabet characters
-w, --wrap=COLS wrap encoded lines after COLS character (default 76).
Use 0 to disable line wrapping

--help display this help and exit
--version output version information and exit

The data are encoded as described for the base64 alphabet in RFC 4648.
When decoding, the input may contain newlines in addition to the bytes of
the formal base64 alphabet. Use --ignore-garbage to attempt to recover
from any other non-alphabet bytes in the encoded stream.

GNU coreutils online help: <http://www.gnu.org/software/coreutils/>
Full documentation at: <http://www.gnu.org/software/coreutils/base64>
or available locally via: info '(coreutils) base64 invocation'

The simplest way to encode is to pipe your source into the base64 command with no added flags. It will then output your encoded text

$ echo 'Hello World' | base64

To decode a block of text that has been base64 encoded, the process is the same, except with the added –decode switch

$ echo 'SGVsbG8gV29ybGQK' | base64 --decode
Hello World