How can I decode a base64 string from the command line?

Solution 1:

Just use the base64 program from the coreutils package:

echo QWxhZGRpbjpvcGVuIHNlc2FtZQ== | base64 --decode

Or, to include the newline character

echo `echo QWxhZGRpbjpvcGVuIHNlc2FtZQ== | base64 --decode`

output (includes newline):

Aladdin:open sesame

Solution 2:

openssl can also encode and decode base64

$ openssl enc -base64 <<< 'Hello, World!'
SGVsbG8sIFdvcmxkIQo=
$ openssl enc -base64 -d <<< SGVsbG8sIFdvcmxkIQo=
Hello, World!

EDIT: An example where the base64 encoded string ends up on multiple lines:

$ openssl enc -base64 <<< 'And if the data is a bit longer, the base64 encoded data will span multiple lines.'
QW5kIGlmIHRoZSBkYXRhIGlzIGEgYml0IGxvbmdlciwgdGhlIGJhc2U2NCBlbmNv
ZGVkIGRhdGEgd2lsbCBzcGFuIG11bHRpcGxlIGxpbmVzLgo=
$ openssl enc -base64 -d << EOF
> QW5kIGlmIHRoZSBkYXRhIGlzIGEgYml0IGxvbmdlciwgdGhlIGJhc2U2NCBlbmNv
> ZGVkIGRhdGEgd2lsbCBzcGFuIG11bHRpcGxlIGxpbmVzLgo=
> EOF
And if the data is a bit longer, the base64 encoded data will span multiple lines.

Solution 3:

Here you go!

Add the following to the bottom of your ~/.bashrc file:

decode () {
  echo "$1" | base64 -d ; echo
}

Now, open a new Terminal and run the command.

decode QWxhZGRpbjpvcGVuIHNlc2FtZQ==

This will do exactly what you asked for in your question.

Solution 4:

With your original dependencies it is possible to do this with a minor modification to your original script:

echo $1 | python -m base64 -d

If you don't pass a file name, that python module reads from the standard input. To pipe the first parameter into it you can use echo $1 |.