33

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

Mark Setchell
  • 169,892
  • 24
  • 238
  • 370
ambikanair
  • 3,231
  • 9
  • 37
  • 66

2 Answers2

68

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

deceze
  • 491,798
  • 79
  • 706
  • 853
14

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
orip
  • 69,626
  • 21
  • 116
  • 145