Reputation: 2359
I am trying to get a base64 encode to work and output to a variable in a bash script. The regular cli syntax is:
echo -ne "\[email protected]\0mypass" | base64
But when I try putting this into a variable in a script it outputs, but a very small encoding, so I know it's not working. My code in the script is:
auth=$(echo -ne "\0$user@$host\0$pass" | base64);
I know it has something to do with the quotes, but I've tried a myriad of thing's with different quotes and singles and backslashes with no go.
Any thoughts?
EDIT: A bit more for the info. This should output with the user/pass/host above:
AG15dXNlckBteWhvc3QuY29tAG15cGFzcw==
But in the script it outputs:
LW5lIAo=
Upvotes: 20
Views: 41766
Reputation: 125928
Different versions of echo
behave very differently when you give them anything other than a plain string. Some interpret command options (like -ne
), while some just print them as output; some interpret escape sequences in the string (even if not given a -e
option), some don't.
If you want consistent behavior, use printf
instead:
user=myuser
pass=mypass
host=myhost.com
auth=$(printf "\0%s@%s\0%s" "$user" "$host" "$pass" | base64)
As a bonus, since the password (and username and host) are in plain strings rather than the format string, it won't make a mess trying to interpret escape sequences in them (does your real password have a backslash in it?)
Upvotes: 14
Reputation: 30197
Ok, I'll add this as an answer for the records's sake:
Problem was in having /bin/sh
as a default interpreter shell, which I assume, in this case was dash
.
Test script used:
#!/bin/bash
user=myuser
pass=mypass
host=myhost.com
auth=$(echo -ne "\0$user@$host\0$pass" | base64);
echo $auth
Results:
[51][00:33:22] vlazarenko@alluminium (~/tests) > echo -ne "\[email protected]\0mypass" | base64
AG15dXNlckBteWhvc3QuY29tAG15cGFzcw==
[52][00:33:42] vlazarenko@alluminium (~/tests) > bash base64.sh
AG15dXNlckBteWhvc3QuY29tAG15cGFzcw==
[53][00:33:46] vlazarenko@alluminium (~/tests) > dash base64.sh
LW5lIAo=
Upvotes: 30