{ Soham Kamani }

About Blog Github Twitter

🌙
☀️

How to Encode and Decode Base64 Data from the Command Line (With Examples)

In this post we wil learn how to encode and decode from the base64 format using the base64 command line tool, typically pre-installed on most Unix base operating systems, like MacOS or Linux.

banner

Installation

The bas64 command is usually pre-installed on most Unix based operating systems. You can check if you already have it installed by opening your terminal and typing:

base64 --help

If installed, you should get some help information printed to your terminal. Otherwise, you can use your operating systems package manager (like apt or brew) to install it manually.

Encoding to Base64

To encode plain text into its base64 format, you can execute:

echo "sample text" | base64

Which will print the base64 output:

c2FtcGxlIHRleHQK

Decoding from Base64

Let’s use the output from the above example to see how to decode it back into plain text.

We can use the -D option to decode from base64:

echo "c2FtcGxlIHRleHQK" | base64 -D

This will print our original string as output:

sample text

Encoding/Decoding Files

We can use the -i and -o options to specify input and output files, respectively.

Consider a file sample.txt in our current directory. If we want to encode the contents of this file into base64, we can run the command:

base64 -i sample.txt -o sample.base64

This will convert the contents of the sample.txt file and store them into a new file sample.base64.

For decoding base64 files, we can run:

base64 -D -i sample.base64 -o sample.out.html

Since Base64 is a binary format, and encodes/decodes directly from binary data, we can use it to convert any type of file (text, video, executable) into Base64 strings


Like what I write? Join my mailing list, and I'll let you know whenever I write another post. No spam, I promise!

Comments