2020年2月9日 星期日

[Linux 常見問題] How to export variables that are set, all at once?

Source From Here
Question
If I defined environment variable(s) in a file, how do I export these variables all at once?

How-To
Assume we have a configuration file .env:
  1. MY_NAME='John'  
  2. MY_AGE='39'  
Then we can test it by test.sh:
  1. #!/bin/sh  
  2. echo -e "===== Setting from .env ====="  
  3. cat .env  
  4.   
  5. echo -e "\n===== My setting ====="  
  6. env | grep 'MY'  
  7.   
  8. source ./.env  
  9. echo -e "\n===== After .env, My setting ====="  
  10. env | grep 'MY'  
The execution result:
# ./test.sh
===== Setting from .env =====
MY_NAME='John'
MY_AGE='39'

===== My setting =====

===== After .env, My setting =====

Run the following command, before setting the variables:
From man page:
-a
When this option is on, the export attribute shall be set for each variable to which an assignment is performed;

To turn this option off, run set +a afterwards. Let's update test.sh:
  1. #!/bin/sh  
  2. echo -e "===== Setting from .env ====="  
  3. cat .env  
  4.   
  5. echo -e "\n===== My setting ====="  
  6. env | grep 'MY'  
  7. set -a  
  8. source ./.env  
  9. set +a  
  10. echo -e "\n===== After .env, My setting ====="  
  11. env | grep 'MY'  
This time, the execution will look like:
# ./test.sh
===== Setting from .env =====
MY_NAME='John'
MY_AGE='39'

===== My setting =====

===== After .env, My setting =====
MY_AGE=39
MY_NAME=John


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...