- Linux Environment Variables Step-By-Step Easy Guide
- Common Environment Variables
- Environment Variable Functions
- Get Environment Variables
- Set Temporary Environment Variable
- Setting Permanent Environment Variables
- Removing Environment Variables
- Closing Thoughts
- ИТ База знаний
- Полезно
- Навигация
- Серверные решения
- Телефония
- Корпоративные сети
- Переменные окружения в Linux: как посмотреть, установить и сбросить
- Переменные окружения и переменные оболочки
- Про Linux за 5 минут
- Вывести список всех переменных окружения и оболочки
- Общий набор переменных окружения в Linux
- Установка переменных окружения в Linux
- Установить постоянные переменные окружения в Linux
- Использование файла .bashrc
- Использование файла .bash_profile
- Использование etc/environment
- Установить переменные окружения в одной строкой
- Сбросить переменные окружения в Linux
- Использование команды unset
- Использование команды set -n
- Установить переменную окружения PATH в Linux
- Заключение
Linux Environment Variables Step-By-Step Easy Guide
In the previous posts, we talked about some of the basic Linux commands, today we continue our journey, and we will talk about something essential in Linux, which is Linux environment variables.
Environment variables are a set of changing values that are baked into every Linux system. They are also used in other Unix-based systems for the very same purposes.
Environment variables are used by scripts and applications in various scenarios. Users and system processes are capable of accessing these environment variables, which is a stark contrast to regular shell variables.
Table of Contents
Common Environment Variables
There exists a large variety of environment variables in the Linux operating system. They can be quite difficult to keep track of and commit to memory.
But it is extremely important that you are aware of the most common ones, as they can be very useful in a wide array of different system administration scenarios, as well as for personal use.
So, as either a brief refresher or an informative list, we’ll provide in easy examples below a complete list of some of the most common environment variables.
- USER – This environment variable is the currently logged user on a Linux system.
- HOME – This environment variable is the home directory of the current user on a Linux system.
- EDITOR – This environment variable is the default editor that is used to edit .txt files in your Linux terminal. This allows for programs to ascertain which text editor it is that you prefer to use for editing Linux applications.
- SHELL – This environment variable is the path of the present user’s shell. Many different shells can be used on a Linux system. A couple of the most common ones are Bash and ZSH. A shell is what interprets the commands you’re typing in, and the syntax and commands will change depending on which one you’re using. For nearly every Linux OS distro, Bash is the default and by far the most popular.
- LOGNAME – This environment variable is just the name of the current user.
- PATH – Containing a colon (:), this environment variable is a list of directories that will be searched when executing a command. When a command is run on the system, it will search those directories in the specified order of the file path. The system will continue to search these directories until it has found the first command that it can execute. Otherwise, you will receive an error message in your terminal that reads “command not found”.
- LANG – This environment variable is the current locale setting.
- TERM – This environment variable is the terminal emulation.
- MAIL – This environment variable is where the current user’s mail will be stored.
These are some of the environment variables that you should familiarize yourself with. It is also necessary to note that variables are case sensitive.
It is important that you make sure that you type the variable name with the right letter casing, otherwise, the output may be completely different.
Though it isn’t too big of a deal to remember as most of the environment variables are in the upper case.
Environment Variable Functions
Environment variables can be used to customize the way the system functions. They can also be used to modify code that tells applications on the system how to behave.
For example, many system applications and user-made scripts require access to the current user’s home directory.
We can achieve this by using the HOME environment. Utilizing HOME for a user made script will allow for any user on the system to run the script.
In this tutorial, we’ll explain how to view the currently configured environment variables and set new variables. Every Linux system has a set of these environment variables.
But you can also set new environment variables for temporary or permanent usage.
Using newly set environment variables is particularly useful when you need the environment variables to remain after a reboot. In the examples below, we’ll show how to employ both methods.
Get Environment Variables
The printenv command is one way to list all environment variables on Linux. You can see how we use its syntax in the Linux terminal in the example provided below.
Printing an entire list of every single environment variable on a Linux system may not be the best idea if you are just looking to get the information of a single variable.
But don’t worry, Linux has yet another convenient solution to a seemingly small problem; you can also use this command to list a specified variable by typing its name following the command.
The syntax for listing a specific variable is shown down below.
Checking specific variables though is not limited to just one at a time. You can also list multiple specific variables at the same time by using the printenv .
The syntax for checking multiple variables simultaneously is the same; you must simply list each environment variable after typing the printenv command. We’ll show an example of its syntax below.
In a Linux system, it is possible to utilize environment variables via command line or inside a Bash script. The way that this can be achieved is by prepending the environment variables with a dollar sign.
One of the most common environment variables that one might edit with is the $PATH variable. The $PATH variable allows the user to specify a directory that the Bash shell should search for applications when you execute commands.
Set Temporary Environment Variable
As we mentioned in an earlier section of this tutorial, we can set new environment variables in Linux. If you’ll also recall, it is possible to set both temporary and permanent variables.
The following command is an example of how to create a temporary environment variable that won’t persist after a user logout, new shell, or when you reboot the system. In the example below, we’ll set a new environment variable called VARIABLE .
Using the following command will create a new shell variable. Though, it is important to note that this environment variable will only be usable in the current terminal.
We’ll show you how to create environment variables in the next couple of examples.
Now that we’ve made a new sample shell variable, we can set this variable as a new environment variable. To set shell variables in your Linux terminal, you’ll need to use the export command.
In the examples above, we showed you how to set temporary environment variables using two separate commands. But like in many other different scenarios in Linux, there exists useful alternatives to make certain operations more efficient and convenient; we can configure the non-persistent environment variable using just a single command with the syntax shown below.
Setting Permanent Environment Variables
As we mentioned in the “Setting Temporary Environment Variables” section of this tutorial, we can configure new environment variables to be both temporary and permanent.
Since we already covered setting temporary environment variables.
We’ll show in the examples below how to configure new environment variables to be persistent. This can be done through a few different files in Linux. The file you choose to edit depends on how exactly you plan to access the environment variables.
/.bashrc – This file exists in the user’s home directory and will store variables that can only be used by the respective user.
These variables will be reloaded any time the user starts a new shell.
/etc/profile – The variables that are stored here can be accessed by every user and will be loaded when a new shell has been opened.
/etc/environment – Variables that are stored here can be accessed system-wide.
Now that although you are aware of the three files where Bash configuration files can be edited through, you might be wondering now how one might put a custom variable inside the
/ .bashrc or /etc/profile configuration files.
We can do this by adding a line to the bottom of either file by using the syntax shown in the example below. Take note that we added export before each new variable.
Upon running this command, you can then reload the edited files into the present session with the command shown in the example down below.
Another thing to note is that if you are placing a new environment variable in the /etc/environment configuration file, you aren’t required to type the export command. An example of the syntax can be seen down below.
The methods that we have shown in the examples above will allow you to make your variable configurations persist until you remove them.
You can also utilize the echo command to print a shell variable. This can be useful if, for example, you are making a script whose purpose is to generate a sample text file in your current user’s home directory. And multiple different users will be running the script.
Then the home directory is gonna change all the time depending on who is running it. The script will check the $HOME variable to see which user’s home directory it should use.
As we explained in an earlier section of this tutorial, the $HOME environment variable is the user’s home directory. This check must be accurate as you won’t be able to run certain operations such as the script in our example if the $HOME is not the correct one.
You can check the $HOME variable for yourself using the command line in your terminal with the echo command. The syntax is provided in the example below.
Throughout this tutorial, we showed you how to set and check Linux environment variables in your terminal by using a variety of commands and methods.
Removing Environment Variables
But you might be wondering what to do if you want to remove an environment variable that you have set. This can be achieved by using the unset command in the Linux terminal.
In Linux, there exists a certain philosophy that is not present in operating systems like Windows, for example. And that’s that there are no operations or processes that can be reversed or undone.
The thinking here is that if something was important and wasn’t supposed to have been erased, it should have been backed up.
So, it is important to note that if you use the unset command, like we just said above, it cannot be undone. Accidentally unsetting and removing an environment variable will cause it to be lost forever. So use this command with extreme care.
Closing Thoughts
In this tutorial, we explored how to set environment variables on Linux and view a list of all existing variables. Environment variables are a helpful aspect in Linux that allows us to access changing information across different systems.
They can be particularly useful for system administrators as they’ll constantly run system processes and programs that need the information that Linux system environment variables carry.
If everything in this post that we have said about environment variables seems like a lot, don’t worry, some things are more important to remember than others.
What you should mainly try to keep in mind are the commands for setting, unsetting, and checking environment variables. These are the main functions of environment variables in Linux that you’ll utilize the most frequently.
Источник
ИТ База знаний
Курс по Asterisk
Полезно
— Узнать IP — адрес компьютера в интернете
— Онлайн генератор устойчивых паролей
— Онлайн калькулятор подсетей
— Калькулятор инсталляции IP — АТС Asterisk
— Руководство администратора FreePBX на русском языке
— Руководство администратора Cisco UCM/CME на русском языке
— Руководство администратора по Linux/Unix
Навигация
Серверные решения
Телефония
FreePBX и Asterisk
Настройка программных телефонов
Корпоративные сети
Протоколы и стандарты
Переменные окружения в Linux: как посмотреть, установить и сбросить
Работа с переменными
Переменные окружения (или переменные среды) — это набор пар ключ-значение, которые хранятся в вашем Linux и используются процессами для выполнения определенных операций. Они отвечают за стандартное поведение системы и приложений. При взаимодействии с вашим сервером через сеанс оболочки, есть много информации, которую ваша оболочка обрабатывает, чтобы определить ее поведение и доступы. Некоторые из этих параметров содержатся в настройках конфигурации, а другие определяются пользовательским вводом. Оболочка отслеживает все эти параметры и настройки через окружение. Окружение — это область, которую оболочка создает каждый раз при запуске сеанса, содержащего переменные, определяющие системные свойства. Например, это может быть часовой пояс в системе, пути к определенным файлам, приложения по-умолчанию, локали и многое другое. Переменные окружения также могут использоваться в программах оболочки или в подоболочках для выполнения различных операций.
Мини — курс по виртуализации
Знакомство с VMware vSphere 7 и технологией виртуализации в авторском мини — курсе от Михаила Якобсена
В этом руководстве мы расскажем, как просматривать, устанавливать и сбрасывать переменные окружения в вашей системе.
Переменные окружения и переменные оболочки
Переменные имеют следующий формат:
Должны соблюдаться следующие правила:
- Имена переменных чувствительны к регистру (регистрозависимы). Переменные окружения должны быть написаны большими буквами (UPPER CASE).
- Несколько значений переменных разделяются двоеточием :
- Вокруг символа = нет пробела
Переменные можно разделить на две категории:
- Переменные окружения (Environmental Variables) — это переменные, которые определены для текущей оболочки и наследуются любыми дочерними оболочками или процессами. Переменные окружения используются для передачи информации в процессы, которые порождаются из оболочки.
- Переменные оболочки (Shell Variables) — это переменные, которые содержатся исключительно в оболочке, в которой они были установлены или определены. Они часто используются для отслеживания эфемерных данных, например, текущего рабочего каталога.
Про Linux за 5 минут
Вывести список всех переменных окружения и оболочки
Мы можем увидеть список всех наших переменных окружения, используя команды env или printenv . В состоянии по умолчанию они должны работать точно так же:
Это типичный вывод как для env , так и для printenv . Разница между этими двумя командами проявляется только в их более конкретной функциональности. Например, с помощью printenv вы можете запросить значения отдельных переменных:
А как посмотреть переменные оболочки?
Для этого можно использовать команду set . Если мы введем set без каких-либо дополнительных параметров, мы получим список всех переменных оболочки, переменных окружения, локальных переменных и функций оболочки:
Тут мы получим гигантский вывод, поэтому стоит использовать less , чтобы разделить содержимое на страницы:
Также для вывода переменной оболочки можно использовать команду echo :
Общий набор переменных окружения в Linux
Посмотрим на общий набор переменных окружения, которые вы можете найти в своей системе.
- USER: текущее имя пользователя, использующего систему
- EDITOR: какая программа запускается для редактирования файла на вашем хосте
- HOME: домашний каталог текущего пользователя
- PATH: список каталогов, разделенных двоеточиями, в которых система ищет команды
- PS1: основная строка приглашения (для определения отображения приглашения оболочки)
- PWD: текущий рабочий каталог
- _: самая последняя команда, выполненная в системе пользователем
- MAIL: путь к почтовому ящику текущего пользователя
- SHELL: оболочка, используемая для интерпретации команд в системе, она может быть много разных (например, bash, sh, zsh или другие)
- LANG: кодировка языка, используемая в системе
- DESKTOP_SESSION: текущий рабочий стол, используемый на вашем хосте (GNOME, KDE)
- HISTFILESIZE: количество строк истории команд, сохраненных в файле истории
- HISTSIZE: количество строк истории, разрешенных в памяти
- UID: текущий UID для пользователя
- HOSTNAME: имя компьютера системы
- TERM: указывает тип терминала
- OLDPWD: предыдущий рабочий каталог
- BASHOPTS: список параметров, которые использовались при выполнении bash.
- BASH_VERSION: версия bash, выполняемая в удобочитаемой форме.
- BASH_VERSINFO: версия bash с машиночитаемым выводом.
- COLUMNS: Количество столбцов в ширину, которые используются для вывода вывода на экран.
- DIRSTACK: стек каталогов, доступных с помощью команд pushd и popd.
- IFS: внутренний разделитель полей для разделения ввода в командной строке. По умолчанию это пробел.
- SHELLOPTS: параметры оболочки, которые можно установить с помощью параметра set.
Установка переменных окружения в Linux
В Linux у вас есть много разных способов установки переменных окружения в зависимости от того, хотите ли вы сделать их постоянными или нет.
Самый простой способ установить переменные окружения — использовать команду export .
Для примера создаим новую переменную, а затем экспортируем ее.
Чтобы создать новую переменную оболочки с именем NEW_VARIABLE и значением «test», и затем сразу экспортировать ее введите:
Используя export , ваша переменная окружения будет установлена для текущего сеанса оболочки. Как следствие, если вы откроете другую оболочку или перезапустите свою систему, переменная окружения больше не будет доступна.
Установить постоянные переменные окружения в Linux
Как вы видели в предыдущем разделе, переменные окружения не были постоянными при перезапуске оболочки. Однако существует способ сделать ваши изменения постоянными: с помощью системных файлов, которые читаются и выполняются в определенных условиях.
Использование файла .bashrc
Самый популярный способ постоянной установки переменных среды — это добавить их в файл .bashrc .
Файл .bashrc — это скрипт, выполняемый всякий раз, когда вы инициализируете сеанс интерактивной оболочки. Как следствие, когда вы запускаете новый терминал через интерфейс GNOME или просто используете screen сессию, вы будете использовать файл .bashrc .
Например, добавьте следующие записи в ваш файл .bashrc :
Сохраните ваш файл и используйте команду source для перезагрузки файла bashrc для текущего сеанса оболочки.
Вы можете вывести новую переменную окружения с помощью printenv и посмотреть, дату в Linux, изменив TZ.
Отлично, ваши изменения теперь сохраняются после перезагрузки оболочки или системы!
Использование файла .bash_profile
В качестве альтернативы, если вы планируете подключаться к своим сеансам с помощью login оболочек, вы также можете добавить переменные окружения непосредственно в файл .bash_profile .
Использование etc/environment
Если вам нужно применить определенные переменные окружения для всех, то определить общесистемные переменные окружения. Чтобы установить общесистемные переменные окружения в Linux, вам нужно экспортировать переменные в файл /etc/environment .
Например, чтобы изменить редактор, используемый глобально, вы можете изменить переменную EDITOR в файле окружения.
Теперь попробуйте войти в систему как под разными пользователями в вашей системе, и вы увидите, что переменная EDITOR установлена для всех на сервере.
Установить переменные окружения в одной строкой
Теперь, когда вы знаете все подробности о том, как устанавливать переменные окружения, вы можете использовать эти шорткаты для их легкой установки.
Сбросить переменные окружения в Linux
Теперь, когда вы установили много переменных окружения в своей системе, вы можете отменить некоторые из них, если вы больше не используете их. В Linux существует два способа сброса переменных окружения: с помощью команды unset или путем удаления записей переменных в ваших системных файлах.
Использование команды unset
Чтобы удалить переменную окружения, используйте команду unset со следующим синтаксисом:
Выглядит это так:
Использование команды set -n
Кроме того, вы можете сбросить переменные окружения, используя команду set с флагом -n -n.
Установить переменную окружения PATH в Linux
В системах Linux очень часто задают переменную окружения PATH , чтобы система могла находить команды.
Чтобы отобразить текущую переменную окружения PATH , выполните команду printenv :
Чтобы установить переменную окружения PATH, добавьте строку export в файл .bashrc и используйте с ним команду source :
Успех! Вы успешно обновили переменную окружения PATH в Linux.
Заключение
В сегодняшнем руководстве вы узнали, что переменные окружения в Linux можно задавать несколькими способами: с помощью команды export , а также путем изменения некоторых системных файлов, чтобы сделать их постоянными.
Вы также узнали, что можно сбросить переменные окружения и как легко обновить переменную окружения PATH .
Мини — курс по виртуализации
Знакомство с VMware vSphere 7 и технологией виртуализации в авторском мини — курсе от Михаила Якобсена
Источник