How to use the command `base64` (with examples)
- Osx
- December 25, 2023
This article will provide a step-by-step guide on how to use the base64
command, including various use cases and their corresponding explanations.
Command Description
The base64
command is used to encode and decode text or files using Base64 representation. Base64 encoding is a way to convert binary data into ASCII characters, which can be easily transmitted over text-oriented protocols such as email or HTTP.
Use case 1: Encode a file
Code:
base64 --input=plain_file
Motivation:
Encoding a file using Base64 can be useful when you need to transfer binary data over text-oriented protocols, such as when sending attachments via email.
Explanation:
--input=plain_file
: Specifies the input file to be encoded.
Example output:
SGVsbG8gd29ybGQ=
Use case 2: Decode a file
Code:
base64 --decode --input=base64_file
Motivation:
Decoding a file encoded with Base64 is necessary when you receive a Base64-encoded file and need to restore its binary data.
Explanation:
--decode
: Instructsbase64
to decode the input file.--input=base64_file
: Specifies the Base64-encoded input file to be decoded.
Example output:
Hello world!
Use case 3: Encode from stdin
Code:
echo -n "plain_text" | base64
Motivation:
Encoding text from stdin
is useful when you want to encode data on the fly or integrate the command into a larger pipeline.
Explanation:
echo -n "plain_text"
: Generates the text to be encoded.|
: Pipes the output of the previous command as input to the next one.base64
: Encodes the input received fromstdin
.
Example output:
cGxhaW5fdGV4dA==
Use case 4: Decode from stdin
Code:
echo -n base64_text | base64 --decode
Motivation:
Decoding a Base64-encoded text from stdin
allows you to restore the original data sent in Base64 format.
Explanation:
echo -n base64_text
: Generates the Base64-encoded text to be decoded.|
: Pipes the output of the previous command as input to the next one.base64 --decode
: Decodes the input received fromstdin
.
Example output:
plain_text
Conclusion
The base64
command is a versatile tool for encoding and decoding data using Base64 representation. Whether you need to encode files or process data from stdin
, understanding and utilizing these use cases will enable you to manipulate Base64 data effectively.