How to Export a Multi-line Environment Variable in Bash/Terminal e.g: RSA Private Key

Deadly 提交于 2019-11-30 11:07:41

export the key

export PRIVATE_KEY=`cat ./gitbu.2018-03-23.private-key.pem` 

test.sh

#!/bin/bash  echo $PRIVATE_KEY; 

If you want to save the key to a .env file with the rest of your environment variables, all you needed to do is "wrap" the private key string in single quotes in the .env file ... e.g: sh exports HELLO_WORLD='-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEA04up8hoqzS1+APIB0RhjXyObwHQnOzhAk5Bd7mhkSbPkyhP1 ... iWlX9HNavcydATJc1f0DpzF0u4zY8PY24RVoW8vk+bJANPp1o2IAkeajCaF3w9nf q/SyqAWVmvwYuIhDiHDaV2A== -----END RSA PRIVATE KEY-----' So the following command will work:

echo "export PRIVATE_KEY='`cat ./gitbu.2018-03-23.private-key.pem`'" >> .env 

Followed by:

source .env 

Now the key will be in your .env file and whenever you source .env it will be exported.

If you want to export direct value (not from *.pem) then use " after equals sign. The terminal will let you finish with another ".

export PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEA04up8hoqzS1+ ... l48DlnUtMdMrWvBlRFPzU+hU9wDhb3F0CATQdvYo2mhzyUs8B1ZSQz2Vy== -----END RSA PRIVATE KEY-----" 

NOTE: For me to get the output to work correctly, I had to wrap the environment variable in double quotes. Otherwise it replaced newlines with spaces.

In:

export PRIVATE_KEY=$(cat ./gitbu.2018-03-23.private-key.pem) 

Out:

echo "$PRIVATE_KEY" 

What I wanted is one and only one executable shell script containing it all, and not 1 script and 1 .pem file and then doing some gymnastics in between, like what I am seeing in the existing answers so far.

To achieve this unification, all that is needed is the following. Preparation phase:

cat id_rsa | base64 -w0 # assign the converted 1-liner string wrap in single quote into a shell variable, for example pk='xxxxxxxxxxxyyyyyyyyyyzzzzzzzzzzz......' 

The rest is walk-in-the park. To ssh using variable pk you will convert back the 1-liner string into its original posture and write to a temporary file.

t=$(mktemp) printf $pk | base64 --decode > $t ssh -i $t smeagol@192.143.69.69 

To clean-up, use the trap:

trap cleanup 1 2 3 6 cleanup () {     rm -f $t } 

To improve security, modify mktemp so write somewhere within your $HOME folder where only you can read, rather than in /tmp where other users in the same server can read.

You can also use a bash heredoc:

export MY_CERTIFICATE=$(cat <<EOF -----BEGIN CERTIFICATE----- qiuwiuwoejqododhIOOISOIIOiiSNIDNIDINDIONDIND DDHDHUDHDUHUhudhHQhhqoohooiiohihiohihhihhihi dhdiodhioho... -----END CERTIFICATE----- EOF ) 

Once you set it you can access it as a regular env variable echo $MY_CERTIFICATE.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!