When you need to transmit complex data (like an image file, a compiled binary executable, or an SSH cryptographic key) through a system that was only designed to handle basic text (like an email body, a JSON API payload, or an XML document), the raw binary data will become corrupted. To solve this, developers use Base64 encoding. Base64 is a universal translation system that takes raw binary data and mathematically translates it into a safe, readable string of 64 standard ASCII characters (A-Z, a-z, 0-9, +, and /). You can easily encode and decode this data directly in the Linux terminal using the base64 command.
How to Encode a File to Base64
To convert an existing file (such as an image named logo.png) into a safe text string, you run the base64 command followed by the filename.
base64 logo.png
When you press Enter, the terminal will instantly print a massive block of seemingly random text (e.g., iVBORw0KGgoAAAANSUhEUgAA...) to the screen. This text block is your image, safely encoded.
Saving the Encoded Data to a File
Printing the encoded string to the terminal screen is rarely useful. Usually, you want to save that text into a new file so you can attach it to an email or paste it into a script. You do this using the standard Linux redirect operator (>).
base64 logo.png > encoded_logo.txt
This command silently encodes the image and writes the resulting text block into a new file named encoded_logo.txt.
How to Decode Base64 Back into a File
When you receive a Base64 encoded string from someone else, you must decode it to reconstruct the original binary file. You do this by passing the -d (decode) flag to the command.
base64 -d encoded_logo.txt > restored_logo.png
This command reads the text file, translates the Base64 string back into raw binary data, and saves it as a brand-new, fully functional image file.
Encoding Text Strings Directly
You do not need to use a file; you can encode a simple text string directly on the command line by piping the output of the echo command into the base64 utility.
echo -n "Hello, World" | base64
Note: The -n flag is critical here; it tells echo not to include a hidden “newline” character at the end of the text, ensuring your Base64 string is perfectly accurate and not corrupted by invisible formatting.