1

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

7
  • Show your shebang and how do you run your script. Commented Oct 22, 2019 at 15:49
  • 1
    Can't reproduce w/ bash 4.4.20 and coreutils 8.28 Commented Oct 22, 2019 at 15:49
  • 1
    Can't reproduce with dash, ksh, csh, zsh. Commented Oct 22, 2019 at 15:52
  • Ah yes, using printf is a great solution ,its behaviour is much less platform dependant than echo's Commented Oct 22, 2019 at 15:57
  • 1
    Why is printf better than echo? Commented Oct 22, 2019 at 16:02

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Note that printf is a bit more complicated to use correctly than echo is. Its first argument is a format string that says how to format what it prints, and the rest are the actual things to print. In this case, I'd use printf "%s:%s" "user" "password" (although printf "%s" "user:password" would also work fine).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.