14

Say I have an image image1.jpg
I can encode it using base64 tool :

myImgStr=$(base64 image1.jpg)

I tried to decode it using the following command:

base64 -i -d $myImgStr > image2.jpg

or

echo -n $myImgStr | base64 -d -i > image2.jpg

But in both cases I get the following error:

base64: extra operand ‘/9j/4AAQSkZJRgABAQAAAQABAAD/7QCEUGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAGgcAmcAFHNH’ Try 'base64 --help' for more information.
Any help is appreciated.

1 Answers1

30

The utility base64 reads its input either from a file whose name is supplied as an argument, or from standard input. It never reads its input from a command line argument. In your case, to decode a string stored in a variable, you should supply the string on the standard input of base64.

If you are using Bash, you may use a here-string:

base64 -d <<< "$myImgStr" > image2.jpg

If your shell does not accept here-strings, you can always use:

echo "$myImgStr" | base64 -d > image2.jpg

(Note the doublequotes around "$myImgStr". You should always doublequote variable expansions unless you have a good reason not to.)

AlexP
  • 10,037
  • 1
  • 32
  • 39
  • 1
    Exactly what I wanted to write. In the second version, it might be useful to emphasize how the variable is enclosed in double quotes (`"$myImgStr"`), which is necessary and missing in the failed attempts listed in the question. – Byte Commander Apr 21 '17 at 21:07
  • Why you used `<<<` instead of `<<` in the first command? –  Apr 21 '17 at 21:12
  • @Navaro: `<<` and `<<<` are different things. `<<` introduces a here-document, and `<<<` a here-string. See [`man bash`](http://manpages.ubuntu.com/manpages/xenial/en/man1/bash.1.html); search for `<<<`. – AlexP Apr 21 '17 at 21:14
  • I think it is `-D` not `-d` – Lucas Goossen Aug 24 '18 at 21:07
  • @LucasGoossen: [manual page for `base64`(1)](http://manpages.ubuntu.com/manpages/bionic/en/man1/base64.1.html). – AlexP Aug 24 '18 at 21:30
  • @AlexP hmm... the man page on macOS 10.13.6 has `-D` and I just noticed we are on "Ask Ubuntu" ha! – Lucas Goossen Sep 06 '18 at 17:35