Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

base64 doesnt have -w option in Mac

I am trying to use base64 but the script doesn't run successfully in Ubuntu machine

MYCOMMAND=$(base64  commands.sh)

So in Ubuntu , I have to use

MYCOMMAND=$(base64 -w0 commands.sh)

unfortunately this option is not there in Mac. How can i write a single script which runs both in Mac and Ubuntu

like image 316
ambikanair Avatar asked Sep 28 '17 07:09

ambikanair


People also ask

How do I decode Base64 on Mac terminal?

If you run base64 –decode without a file, you can type text (or copy and paste it), hit return/enter, and then control+d / ctrl+d and it will be decoded.

How do I find Base64 encoding?

In base64 encoding, the character set is [A-Z, a-z, 0-9, and + /] . If the rest length is less than 4, the string is padded with '=' characters. ^([A-Za-z0-9+/]{4})* means the string starts with 0 or more base64 groups.

Does SMTP use Base64?

Base64 is also widely used for sending e-mail attachments. This is required because SMTP – in its original form – was designed to transport 7-bit ASCII characters only.


2 Answers

Yes, the default macOS base64 implementation doesn't have the -w flag. What does that flag do?

-w, --wrap=COLS

Wrap encoded lines after COLS character (default 76). Use 0 to disable line wrapping.

And here's the macOS man page for base64:

-b count
--break=count

Insert line breaks every count characters. Default is 0, which generates an unbroken stream.

So, the flag is called -b in macOS, and it already defaults to 0, which means base64 in macOS has the same behaviour as base64 -w0 on Linux. You'll have to detect which platform you run on to use the appropriate variation of the command. See here: Detect the OS from a Bash script; the platform name you're looking for for macOS is "Darwin".

like image 63
deceze Avatar answered Oct 28 '22 20:10

deceze


In Mac's it's -b, and the default is already 0.

$ man base64
...
OPTIONS
     The following options are available:
     -b count
     --break=count        Insert line breaks every count characters. Default is 0, which generates an unbroken stream.
...

One way to have the script work for both is checking for errors:

MYCOMMAND=$(base64 -w0 commands.sh)
if [ $? -ne 0 ]; then
  MYCOMMAND=$(base64 commands.sh)
fi

You can also run an explicit test, e.g

echo | base64 -w0 > /dev/null 2>&1
if [ $? -eq 0 ]; then
  # GNU coreutils base64, '-w' supported
  MYCOMMAND=$(base64 -w0 commands.sh)
else
  # Openssl base64, no wrapping by default
  MYCOMMAND=$(base64 commands.sh)
fi
like image 28
orip Avatar answered Oct 28 '22 19:10

orip