Quick Tip: Base64 Encode and Decode in the Terminal


This is a tip on how to encode and decode text using Base64 in the Linux terminal. Base64 is a way of representing binary data (such as images or files) as text, so that you can easily transfer or store it. For example, you can use Base64 to embed an image in an HTML file without using a separate file.

To encode text using Base64, you can use the base64 command with the -w option to specify the line width. For example, if you want to encode the text “Hello world” with a line width of 10 characters, you can type:

base64 -w 10 <<< "Hello world"

This will output:


To decode text using Base64, you can use the base64 command with the -d option. For example, if you want to decode the text “SGVsbG8gd29ybGQK”, you can type:

base64 -d <<< "SGVsbG8gd29ybGQK"

This will output:

Hello world

You can also use the base64 command to encode or decode files. For example, if you have an image file called image.jpg and you want to encode it as Base64, you can type:

base64 -w 0 image.jpg > image.txt

This will create a file called image.txt that contains the Base64 representation of the image. To decode it back to an image file, you can type:

base64 -d image.txt > image.jpg

That’s it for today’s quick tip. I hope you learned something new and useful. If you have any questions or feedback, feel free to leave a comment below. Thanks for reading and happy coding!

P.S. PowerShell

If you happen to ever use PowerShell, it also has a way to do that. It’s actually very easy, thanks to some built-in commands. Let me show you an example.

Let’s say you have a file called image.jpg that you want to base64 encode. You can use the following command to do that:

$base64 = [Convert]::ToBase64String((Get-Content -Path image.jpg -Encoding Byte))

This will read the file as bytes and convert them to base64 string. You can then save the string to a file or use it however you want.

To decode a base64 string back to bytes, you can use the following command:

$bytes = [Convert]::FromBase64String($base64)

This will convert the base64 string back to bytes. You can then save the bytes to a file or use them however you want.

And that’s it! That’s how you base64 encode and decode in PowerShell. I hope you found this tip useful and stay tuned for more!

To contact me, send an email anytime or leave a comment below.