Linux добавить переменную окружения навсегда

How can I permanently export a variable in Linux?

That variable is lost when the terminal is closed. How do I permanently add this so that this variable value always exists with a particular user?

6 Answers 6

You can add it to your shell configuration file, e.g., $HOME/.bashrc or more globally in /etc/environment.

After adding these lines, the changes won’t reflect instantly in GUI-based systems. You have to exit the terminal or create a new one and on the server, log out the session and log in to reflect these changes.

@mini-me — ~/bashrc is pulled each time you open a shell. To load it explicitly, use source e.g. — > source ~/.bashrc .

@mini-me: the environment of a process is usually set by the caller and changed from within the process. Changing env from outside a running process is unusual and not doable with export , but try with a debugger

@Mr.Hyde: It usually doesn’t matter. Files are parsed from top to bottom, so if a var definition depends on another, they should be ordered accordingly. So yes the end of the file is fine.

just note Shell config files such as ~/.bashrc, ~/.bash_profile, and ~/.bash_login are often suggested for setting environment variables. While this may work on Bash shells for programs started from the shell, variables set in those files are not available by default to programs started from the graphical environment in a desktop session. from help.ubuntu.com/community/EnvironmentVariables

You have to edit three files to set a permanent environment variable as follow:

~/.bashrc

When you open any terminal window this file will be run. Therefore, if you wish to have a permanent environment variable in all of your terminal windows you have to add the following line at the end of this file:

~/.profile

/etc/environment

If you want your environment variable in every window or application (not just terminal window) you have to edit this file. Add the following command at the end of this file:

Normally you have to restart your computer to apply these changes. But you can apply changes in bashrc and profile by these commands:

$ source ~/.bashrc $ source ~/.profile 

But for /etc/environment you have no choice but restarting (as far as I know)

A Simple Solution

I’ve written a simple script for these procedures to do all those work. You just have to set the name and value of your environment variable.

#!/bin/bash echo "Enter variable name: " read variable_name echo "Enter variable value: " read variable_value echo "adding " $variable_name " to environment variables: " $variable_value echo "export "$variable_name"="$variable_value>>~/.bashrc echo $variable_name"="$variable_value>>~/.profile echo $variable_name"="$variable_value>>/etc/environment source ~/.bashrc source ~/.profile echo "do you want to restart your computer to apply changes in /etc/environment file? yes(y)no(n)" read restart case $restart in y) sudo shutdown -r 0;; n) echo "don't forget to restart your computer manually";; esac exit 

Save these lines in a shfile then make it executable and just run it!

Читайте также:  Manjaro linux change kernel

Источник

Как установить переменные среды в Linux

Установка переменных среды в Linux — хороший способ определить общие и повторяющиеся переменные, которые используются во многих приложениях и командах терминала. Эти переменные среды помогают сократить количество подробностей, упростить использование и улучшить рабочий процесс разработки.

Переменная среды в Linux может использоваться для передачи информации или влияния на поведение приложения или процесса. В этой статье будут объяснены различные способы установки переменных среды и их использования.

Чтобы установить переменную среды для используемой в данный момент оболочки, определите переменную в следующем формате:

Определение не требует пояснений, «MYVAR» — это имя переменной, а «xyz» — ее значение. Выполнение приведенной ниже команды проверит правильность установки переменной среды:

Обратите внимание на синтаксис переменных среды. Хотя они работают так же, как и любые другие переменные оболочки, обычно рекомендуется использовать заглавные буквы и подчеркивания для левой стороны (имя переменной).

Чтобы отключить переменную, используйте команду ниже:

Если вы снова проверите переменную с помощью упомянутой выше команды echo, вывод не будет отображаться. Обратите внимание, что unset будет работать только для текущего сеанса терминала. Если в вашей системе определены какие-либо глобальные общесистемные переменные среды, они будут снова доступны в новом сеансе терминала.

Чтобы установить переменную среды для используемой в данный момент оболочки, а также для любых дочерние процессы/оболочки, запущенные из него, используйте переменную в следующем формате:

Чтобы навсегда установить переменную среды для оболочек bash (большинство терминальных приложений по умолчанию в дистрибутивах Linux настроены для оболочки bash), добавьте переменную (с ключевым словом «экспорт») в конец скрытого файла .bashrc в вашем домашнем каталоге.

Вы можете редактировать файл .bashrc, выполнив следующую команду:

Замените «subl» на команду вашего любимого текстового редактора. Вам нужно будет перезагрузить файл .bashrc, чтобы изменения вступили в силу. Для этого выполните команду ниже:

Ниже приведен пример настраиваемых переменных среды I установлены для Ruby Gems.

Вы можете просматривать всю среду переменные, включенные в вашей системе, выполнив команду ниже:

Чтобы специально проверить, добавлена ​​ли настраиваемая переменная среды в Включен файл .bashrc или нет, выполните следующую команду:

Чтобы установить переменную среды для всей системы для всех приложений, оболочек и процессов, добавьте свою пользовательскую переменную в файл«/etc/environment »без ключевого слова« export ».

Вы можете отредактировать файл «/etc/environment», выполнив следующую команду:

Замените «subl» своим любимым текстовым редактором. Возможно, вам потребуется перезагрузить систему, чтобы изменения вступят в силу. Чтобы проверить, правильно ли установлена ​​ваша пользовательская переменная, выполните следующую команду:

Читайте также:  Hackrf one kali linux

В качестве альтернативы вы можете использовать команду «printenv» для проверки изменений:

Обратите внимание, что описанная выше команда «unset» работает для всех настраиваемых переменных среды, независимо от того, являются ли они переменными для конкретного сеанса или глобальными. . Однако unset удаляет переменную только для текущего сеанса оболочки и не удаляет y общесистемная или глобальная переменная на постоянной основе.

Некоторые из предопределенных переменных среды в Ubuntu включают:

  • USER — имя вошедшего в систему пользователя
  • HOME — домашний каталог вошедшего в систему пользователя (обычно/home/username)
  • DISPLAY — активный монитор в использовании (обычно автоматически устанавливается менеджером входа в систему)
  • PWD — рабочий каталог, в котором оболочка используется или вызывается
  • SHELL — оболочка, которая используется в масштабе всей системы (обычно/bin/bash)
  • LANG — язык, используемый системой (определяется пользователем, может быть изменен)
  • PATH — скрипты/двоичные файлы/исполняемые файлы ищутся в каталогах, заданных в переменной PATH

Некоторые из переменных среды, которые обычно используются для влияния на поведение приложения:

  • LC_ALL — принудительно переопределяет определенный пользователем языковой стандарт со значением, указанным в переменной
  • LD_LIBRARY_PATH — используется для определения дополнительных каталогов, в которых будут искать библиотеки времени выполнения.
  • PATH — используется для определить дополнительные каталоги, в которых будет выполняться поиск сценариев/двоичных файлов/исполняемых файлов.
  • LD_PRELOAD — используется для загрузки пользовательских/пониженных/обновленных библиотек в приложении

Это отмечает конец этой статьи. Переменные среды в Linux помогают запускать настроенные команды и приложения без фактического изменения исходного кода и двоичных файлов, предоставляя способ определения и использования глобальных переменных в системе.

Источник

How to permanently set environmental variables

The other answers on this page are great. One small recommendation would be to add /usr/lib/oracle/11.2/client64/lib in a new file under the /etc/ld.so.conf.d/ path. Then you don’t need to set LD_LIBRARY_PATH, see also here.

4 Answers 4

You can add it to the file .profile or your login shell profile file (located in your home directory).

To change the environmental variable «permanently» you’ll need to consider at least these situations:

bash

  1. Bash as login shell will load /etc/profile , ~/.bash_profile , ~/.bash_login , ~/.profile in the order
  2. Bash as non-login interactive shell will load ~/.bashrc
  3. Bash as non-login non-interactive shell will load the configuration specified in environment variable $BASH_ENV
$EDITOR ~/.profile #add lines at the bottom of the file: export LD_LIBRARY_PATH=/usr/lib/oracle/11.2/client64/lib export ORACLE_HOME=/usr/lib/oracle/11.2/client64 

zsh

$EDITOR ~/.zprofile #add lines at the bottom of the file: export LD_LIBRARY_PATH=/usr/lib/oracle/11.2/client64/lib export ORACLE_HOME=/usr/lib/oracle/11.2/client64 

fish

set -Ux LD_LIBRARY_PATH /usr/lib/oracle/11.2/client64/lib set -Ux ORACLE_HOME /usr/lib/oracle/11.2/client64 

ksh

$EDITOR ~/.profile #add lines at the bottom of the file: export LD_LIBRARY_PATH=/usr/lib/oracle/11.2/client64/lib export ORACLE_HOME=/usr/lib/oracle/11.2/client64 

bourne

$EDITOR ~/.profile #add lines at the bottom of the file: LD_LIBRARY_PATH=/usr/lib/oracle/11.2/client64/lib ORACLE_HOME=/usr/lib/oracle/11.2/client64 export LD_LIBRARY_PATH ORACLE_HOME 

csh or tcsh

$EDITOR ~/.login #add lines at the bottom of the file: setenv LD_LIBRARY_PATH /usr/lib/oracle/11.2/client64/lib setenv ORACLE_HOME /usr/lib/oracle/11.2/client64 

If you want to make it permanent for all users, you can edit the corresponding files under /etc/ , i.e. /etc/profile for Bourne-like shells, /etc/csh.login for (t)csh, and /etc/zsh/zprofile and /etc/zsh/zshrc for zsh.

Читайте также:  What are semaphores linux

Another option is to use /etc/environment , which on Linux systems is read by the PAM module pam_env and supports only simple assignments, not shell-style expansions. (See Debian’s guide on this.)

These files are likely to already contain some assignments, so follow the syntax you see already present in your file.

Make sure to restart the shell and relogin the user, to apply the changes.

If you need to add system wide environment variable, there’s now /etc/profile.d folder that contains sh script to initialize variable.
You could place your sh script with all you exported variables here.
Be carefull though this should not be use as a standard way of adding variable to env on Debian.

[Admin@localhost etc]$ cat ~/.profile cat: /home/Admin/.profile: No such file or directory [Admin@localhost etc]$

@user3021349 I don’t meant to be rude but if you think one second you can also use a different editor you master. :wq is the command to write file and exit in vi don’t forget to type esc before

You’ll need to consider the environment variables in crontab scripts. None of these locations will be looked up when a crontab script is running.

To do if for all users/shells, depending on distro you could use /etc/environment or /etc/profile . Creating a new file in /etc/profile.d may be preferable if it exists, as it will be less likely to conflict with updates made by the packaging system.

In /etc/environment , variables are usually set with name=value , eg:

ORACLE_HOME=/usr/lib/oracle/11.2/client64 

In /etc/profile , you must use export since this is a script, eg:

export ORACLE_HOME=/usr/lib/oracle/11.2/client64 

Same goes for a file under /etc/profile.d , there also may be naming restrictions which must be met for the file to work. On Debian, the file must have the extension .sh (although does not need a bang line or executable permissions since it is sourced). check your distro documentation or look at the /etc/profile script to see how these files are loaded.

Note also though that setting LD_LIBRARY_PATH permanently is potentially problematic, including being a security risk. As an alternative, I would suggest finding some way to prepend the LD_LIBRARY_PATH to the start of the command line for each program that needs it before running. Eg:

LD_LIBRARY_PATH=/usr/lib/oracle/11.2/client64/lib myprog 

One way to do this is to use a wrapper script to run the program. You could give this the same name as your program and put it in /usr/local/bin or anywhere that appears before the location of your program in PATH . Here is an example script (don’t forget to chmod +x the script):

#!/bin/sh LD_LIBRARY_PATH=/usr/lib/oracle/11.2/client64/lib /real/location/of/myprog "$@" 

Источник

Оцените статью
Adblock
detector