base64 doesnt have -w option in Mac

Posted on Dec 26, 2022

Question

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

Answer

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".