Reputation: 41
I'm attempting to base64 encode a user:password string in a bash script, however the results in the script are different than if I run the command in a shell.
In shell (expected output):
echo -n "user:password" | base64
dXNlcjpwYXNzd29yZA==
In script (w/ -n):
USER=$(echo -n "user:password" | base64)
echo $USER
LW4gdXNlcjpwYXNzd29yZAo=
In script (w/o -n, extra character at end):
USER=$(echo "user:password" | base64)
echo $USER
dXNlcjpwYXNzd29yZAo=
Can someone tell me what I'm missing here. Thanks
Upvotes: 1
Views: 3179
Reputation: 24812
By using a #!/bin/sh
shebang, you're most likely asking bash
(or whichever shell is behind /bin/sh
which nowadays is almost always a link to another shell) to execute your script in a POSIX-compliant mode :
If bash is invoked with the name sh, it tries to mimic the startup behavior of historical versions of sh as closely as possible, while conforming to the POSIX standard as well.
Your problem is that POSIX echo
does not define a -n
flag, so it is understood in your command as just another parameter to display in your output. Indeed, LW4gdXNlcjpwYXNzd29yZAo=
is the base64 encoding of -n user:password
.
You should use printf
instead of echo
, whose behaviour is much better defined and varies less between implementations.
Moreover, unless you need your script to be portable and possibly run on platforms where bash
isn't available, I suggest you use a #!/usr/bin/env bash
shebang instead of your #!/bin/sh
one so you get to enjoy the bash
goodies.
Upvotes: 6