43

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
  • 191,897
  • 31
  • 273
  • 432
ambikanair
  • 4,004
  • 11
  • 43
  • 83

3 Answers3

87

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
  • 510,633
  • 85
  • 743
  • 889
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
  • 73,323
  • 21
  • 116
  • 148
1

One solution that works in both Linux and MacOS is to use tr:

MYCOMMAND=$(base64 commands.sh | tr -d '\n')
Eric
  • 1,138
  • 11
  • 24