bash 如何在 Linux 中以编程方式设置永久环境变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2891972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:07:30  来源:igfitidea点击:

How to programmatically set a permanent environment variable in Linux?

linuxinstallerenvironment-variablesbash

提问by Richard H

I am writing a little install script for some software. All it does is unpack a target tar, and then i want to permanently set some environment variables - principally the location of the unpacked libs and updating $PATH. Do I need to programmatically edit the .bashrcfile, adding the appropriate entries to the end for example, or is there another way? What's standard practice?

我正在为某些软件编写一个小安装脚本。它所做的只是解压目标 tar,然后我想永久设置一些环境变量——主要是解压库的位置和更新 $PATH。我是否需要以编程方式编辑.bashrc文件,例如在末尾添加适当的条目,还是有其他方法?什么是标准做法?

Edit:The package includes a number of run scripts (20+) that all use these named environment variables, so I need to set them somehow (the variable names have been chosen such that a collision is extremely unlikely)

编辑:该包包含许多运行脚本(20+),它们都使用这些命名的环境变量,所以我需要以某种方式设置它们(已选择变量名,这样碰撞的可能性极小)

回答by P Shved

LSB-compliant (see spec) practice is to create a shell script in /etc/profile.d/folder.

符合 LSB(见规范)的做法是在/etc/profile.d/文件夹中创建一个 shell 脚本 。

Name it after your application (and make sure that the name is unique), make sure that the name ends with .sh(you might want to add scripts for other shells as well) and exportthe variables you need in the script. All *.shscripts from that directory are read at user login--the same time /etc/profileis sourced.

以您的应用程序命名(并确保名称唯一),确保名称以.sh(您可能还想为其他 shell 添加脚本)和export脚本中所需的变量结尾。*.sh在用户登录时读取该目录中的所有脚本——同时/etc/profilesourced。

Note that this is not enforced by bash; rather, it's an agreement of sorts.

请注意,这不是由bash;强制执行的。相反,这是一种协议。

回答by WhirlWind

Standard practice is to install into directories already in the path and in the standard library directory, so there is no need to update these variables.

标准做法是安装到路径和标准库目录中已有的目录中,因此无需更新这些变量。

Updating .bashrc is a bit failure-prone, among other things; what if a user uses a different file or shell?

除其他外,更新 .bashrc 有点容易失败;如果用户使用不同的文件或外壳怎么办?

回答by lhf

You can also generate and install a script that sets those variables. Users of your package then source that script or copy its contents to their own shell init file.

您还可以生成并安装设置这些变量的脚本。您的包的用户然后获取该脚本或将其内容复制到他们自己的 shell init 文件中。