3

I have a username and password variables. I want to encode them to base64 with the format of username:password.

#!/bin/bash
username=username
password=password

echo Encoding username/password...
echo $username:$password | base64

That works, but I'm not sure how to put the output in a variable instead of writing it to the console.

On a side note, why is the output different than a website like https://www.base64encode.org/?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Gilbert Williams
  • 970
  • 2
  • 10
  • 24
  • How this question is even a duplicate of https://stackoverflow.com/questions/49308934/get-base64-version-of-password is beyond me. I mean, this one asks specifically about assigning the output to a variable, whilst the other is merely trying to understand why the command isn't working. Not only that, but its existing answers don't show how to register the output into a variable either. They're two different questions. – Clockwork Jun 13 '22 at 08:55

1 Answers1

7

Using $( ... ), store the result in a variable. And use -n to not include LF.

var=$(echo -n $username:$password | base64)
etsuhisa
  • 1,698
  • 1
  • 5
  • 7
  • 10
    Avoid `echo -n` which is not standard. Prefer `printf instead`: `var=$(printf '%s:%s' "$username" "$password" | base64)` – Léa Gris Apr 03 '21 at 12:27