So please use echo -n
to remove the line break before redirecting to base64
; and use base64 -w 0
to prevent base64
itself to add line break into the output.
me@host:~
$ echo -n mypassword | base64 -w 0
bXlwYXNzd29yZA==me@host:~ # <<<<<<<<<<<<<<< notice that no line break added after "==" due to '-w 0'; so me@host is on the same line
$ echo -n 'mypassword' | base64 -w 0
bXlwYXNzd29yZA==me@host:~ # <<<<<<<<<<<<<<<<<< notice adding single quotes does not affect output, so you can use values containing spaces freely
A good way to verify is using od -c
to show the actual chars.
me@host:~
$ echo -n bXlwYXNzd29yZA== | base64 -d | od -c
0000000 m y p a s s w o r d
0000012
You see no "\n" is added. But if you use "echo" without "-n", od
will show "\n":
me@host:~
$ echo mypassword | base64 -w 0
bXlwYXNzd29yZAo=me@host:~
$ echo bXlwYXNzd29yZAo= | base64 -d | od -c
0000000 m y p a s s w o r d \n
0000013
At last, create a function will help you in the future:
base64-encode() {
if [ -z "$@" ]; then
echo "Encode string with base64; echoing without line break, and base64 does not print line break neither, to not introducing extra chars while redirecting. Provide the string to encode. "
return 1
fi
echo -n "$@" | base64 -w 0 # here I suppose string if containing space is already quoted
}