Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically set a permanent environment variable in Linux?

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 .bashrc file, adding the appropriate entries to the end for example, or is there another way? What's standard practice?

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)

like image 829
Richard H Avatar asked May 23 '10 13:05

Richard H


People also ask

How do I permanently set an environment variable in Linux?

To make the change permanent, enter the command PATH=$PATH:/opt/bin into your home directory's . bashrc file. When you do this, you're creating a new PATH variable by appending a directory to the current PATH variable, $PATH .

How do I set an environment variable in Linux terminal?

To set an environment variable, use the command " export varname=value ", which sets the variable and exports it to the global environment (available to other processes). Enclosed the value with double quotes if it contains spaces. To set a local variable, use the command " varname =value " (or " set varname =value ").


2 Answers

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

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 export the variables you need in the script. All *.sh scripts from that directory are read at user login--the same time /etc/profile is sourced.

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

like image 164
P Shved Avatar answered Sep 17 '22 12:09

P Shved


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?

like image 38
WhirlWind Avatar answered Sep 17 '22 12:09

WhirlWind