简体   繁体   English

如何使用Shell脚本.sh设置全局环境变量

[英]How to set global environment variables using shell script .sh

I have a .sh file that locally sets some environment variables in my shell source my_env.sh . 我有一个.sh文件,可在我的shell source my_env.sh中本地设置一些环境变量。

#!/bin/sh
echo "Setting up local environment variables"
export MY_URL="http://domain.com"
echo "Done"

This only sets the variables for that session. 这仅设置该会话的变量。 Which means that my Python Celery and Supervisor apps which run under a different session cannot access them. 这意味着我在不同会话下运行的Python Celery和Supervisor应用程序无法访问它们。 I understand I can run them under a user, but I want to know if on Ubuntu using the same shell script above if I can set the variables so they are globally accessible to all applications regardless of users or session? 我知道我可以在用户下运行它们,但是我想知道是否可以在Ubuntu上使用与上面相同的Shell脚本设置变量,以便所有应用程序都可以全局访问它们,而不管用户或会话如何?

export your variables in the "/etc/profile". 在“ / etc / profile”中导出变量。

NOTE: This will make it global for each shell sessions for any user. 注意:这将使它对于任何用户的每个Shell会话都是全局的。 If you wish to set this variable for every session for a specific user , set it in that user's "~/.profile". 如果要为特定用户的每个会话设置此变量,请在该用户的“〜/ .profile”中进行设置。

According to Ubuntu env variables doc the best way would be 根据Ubuntu env变量doc ,最好的方法是

A suitable file for environment variable settings that affect the system as a whole (rather than just a particular user) is /etc/environment / etc / environment适用于影响整个系统(而不只是特定用户)的环境变量设置的文件

That's assuming you don't mind having them set for the whole machine. 假设您不介意为整个机器设置它们。

If you are using bashrc or zshrc you can source the shell file which sets the environment variables across the sessions or precisely loads all the environment variables in each session. 如果您使用的是bashrc或zshrc,则可以获取shell文件,该shell文件在整个会话中设置环境变量,或在每个会话中精确加载所有环境变量。

source location/shell-script-sets-env.sh  

The zshrc and bashrc is available in your $HOME directory. zshrc和bashrc在$ HOME目录中可用。 or ~/.zshrc and ~/.bashrc. 或〜/ .zshrc和〜/ .bashrc。 The current shell can be looked via 当前的外壳可以通过以下方式查看

echo $SHELL 

Have a look at setting env permanently for adding it to the profile. 查看将环境永久设置为将其添加到配置文件中的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM