Base64 Encode & Decode in Bash
Encode or decode below — it runs locally in your browser — then grab the canonical Bash code. The base64 command ships on almost every Unix-like system, but watch the echo trap: by default echo appends a trailing newline that changes the encoded output.
Encode and decode a string
Pipe text into the base64 command to encode, and add -d to decode:
$ echo -n "Hello, world!" | base64 SGVsbG8sIHdvcmxkIQ== $ echo "SGVsbG8sIHdvcmxkIQ==" | base64 -d Hello, world!
Tip: ALWAYS use echo -n — without -n, echo appends a trailing newline that changes the Base64 output. The decode flag is -d on GNU/Linux and -D on macOS (BSD).
Avoid line wrapping
GNU base64 wraps output at 76 characters by default. For a single line — needed for env vars and tokens — disable wrapping:
# GNU / Linux: single-line output, no wrapping $ echo -n "Hello, world!" | base64 -w 0 # BSD / macOS: no -w flag, so strip newlines portably $ echo -n "Hello, world!" | base64 | tr -d '\n'
Encode a file / env vars
Pass a filename straight to base64 (no echo, so no newline trap), then store it in a variable:
# encode a file to a single line $ base64 -w 0 key.pem > key.b64 # store it in an env var, then decode at the point of use $ export KEY_B64=$(base64 -w 0 key.pem) $ printf "%s" "$KEY_B64" | base64 -d > key.pem
Frequently asked questions
How do I Base64 encode a string in Bash?
Pipe it into the base64 command with echo -n: echo -n "Hello, world!" | base64 returns SGVsbG8sIHdvcmxkIQ==.
How do I Base64 decode in Bash?
Add the decode flag: echo "SGVsbG8sIHdvcmxkIQ==" | base64 -d (-D on macOS) returns the original text.
How do I avoid line wrapping in Base64 output?
On Linux use base64 -w 0; on BSD/macOS there is no -w, so pipe through tr -d '\n' to get a single line.
Why does my Base64 have an extra character / wrong output?
Because echo without -n appends a trailing newline, so you encode your text plus a \n byte. Always use echo -n or printf "%s".
Need image, file, or URL-safe modes?
The main base64.dev tool handles text, images, files, and URL-safe Base64 with auto-detect.
Open base64.dev →