如何在Bash/终端导出多行环境变量(如RSA私钥)
I totally get your frustration—dealing with newline characters in environment variables is a classic pain point, especially when you're just trying to get an app up and running. Let's skip the complex scripts and use simple, terminal-friendly solutions that even beginners can follow.
Why Your Original Command Failed
First, quick context: When you pasted the private key directly into export, the actual newline characters in the key told your shell, "Okay, this command is done—now run whatever comes next." That's why you got the -----END RSA PRIVATE KEY-----': not a valid identifier error: the shell tried to treat the end of the key as a new command, which it wasn't.
Solution 1: One-Liner to Export the Key Immediately
Use this single terminal command to read your private key file, convert its newlines to escaped \n characters (which the shell can safely store in an environment variable), and export it:
export PRIVATE_KEY="$(cat ./gitbu.2018-03-23.private-key.pem | tr '\n' '\\n')"
How it works:
cat ./gitbu.2018-03-23.private-key.pem: Reads your private key file.tr '\n' '\\n': Replaces every real newline (\n) with an escaped newline (\\n), so the shell doesn't interpret them as command breaks.- The entire output is wrapped in double quotes, ensuring it's treated as a single value for the environment variable.
To verify it worked, run echo "$PRIVATE_KEY"—you should see your full private key, formatted correctly.
Solution 2: Even Simpler (If Your App Accepts It)
Some tools accept private keys with spaces instead of newlines. If github-backup supports this, use this shorter command:
export PRIVATE_KEY="$(cat ./gitbu.2018-03-23.private-key.pem | tr '\n' ' ')"
This just replaces all newlines with spaces, creating a single-line key that's easy to export. Test it with your app first to make sure it works!
Solution 3: Make the Environment Variable Permanent
If you don't want to run the export command every time you open a terminal, add the key to your shell's configuration file:
- Run this command to append the escaped key to your
.bashrc(use.zshrcif you use Zsh):
echo "export PRIVATE_KEY=\"$(cat ./gitbu.2018-03-23.private-key.pem | tr '\n' '\\n')\"" >> ~/.bashrc
- Apply the changes immediately with:
source ~/.bashrc
Now every time you open a terminal, PRIVATE_KEY will be available automatically.
内容的提问来源于stack exchange,提问作者nelsonic

