Linux delete export variable

Содержание
  1. How To – Linux Set Environment Variables Command
  2. Two types of shell variables
  3. Display current environment variables on Linux
  4. env command
  5. How to set and list environment variables in Linux using set command
  6. ИТ База знаний
  7. Полезно
  8. Навигация
  9. Серверные решения
  10. Телефония
  11. Корпоративные сети
  12. Переменные окружения в Linux: как посмотреть, установить и сбросить
  13. Переменные окружения и переменные оболочки
  14. Про Linux за 5 минут
  15. Вывести список всех переменных окружения и оболочки
  16. Общий набор переменных окружения в Linux
  17. Установка переменных окружения в Linux
  18. Установить постоянные переменные окружения в Linux
  19. Использование файла .bashrc
  20. Использование файла .bash_profile
  21. Использование etc/environment
  22. Установить переменные окружения в одной строкой
  23. Сбросить переменные окружения в Linux
  24. Использование команды unset
  25. Использование команды set -n
  26. Установить переменную окружения PATH в Linux
  27. Заключение
  28. How To Read and Set Environmental and Shell Variables on Linux
  29. Introduction
  30. How the Environment and Environmental Variables Work
  31. Printing Shell and Environmental Variables
  32. Common Environmental and Shell Variables
  33. Setting Shell and Environmental Variables
  34. Creating Shell Variables
  35. Creating Environmental Variables
  36. Demoting and Unsetting Variables
  37. Setting Environmental Variables at Login
  38. The Difference between Login, Non-Login, Interactive, and Non-Interactive Shell Sessions
  39. Implementing Environmental Variables
  40. Conclusion

How To – Linux Set Environment Variables Command

  1. Configure look and feel of shell.
  2. Setup terminal settings depending on which terminal you’re using.
  3. Set the search path such as JAVA_HOME, and ORACLE_HOME.
  4. Create environment variables as needed by programs.
  5. Run commands that you want to run whenever you log in or log out.
  6. Set up aliases and/or shell function to automate tasks to save typing and time.
  7. Changing bash prompt.
  8. Setting shell options.
Tutorial details
Difficulty level Easy
Root privileges No
Requirements Linux
Est. reading time 11 minutes

Two types of shell variables

  • Environment variables (GLOBAL): Typically, end-users shouldn’t mess with Environment variables as they are available system-wide, and subshells and child processes can access them. In certain scenarios, we can modify them as per our needs. For example, we set up a system-wide path for the JAVA app or PATH for searching binaries. In almost all cases, we use the export command to define or modify environment variables.
  • Shell and user-defined variables (LOCAL) : As the name suggests, these are defined by users and currently apply to the current shell session.

You can use the following commands to view and configure the environment.

Display current environment variables on Linux

The printenv command shows all or the given environment variables. Open the terminal prompt and then type:
printenv
printenv VAR_NAME
printenv PS1
printenv ORACLE_HOME
printenv JAVA_HOME
# use the grep command/egrep command to filter out variables #
printenv | grep APP_HOME
printenv | egrep ‘APP_HOME|DOCKER_HOME|NIX_BACKUP_HOST’

env command

The env command runs a Linux command with a modified environment. The syntax is:

Please note that If no command name is specified following the environment specifications, the resulting environment is displayed on screen. This is like specifying the printenv command as discussed earlier. For example:

How to set and list environment variables in Linux using set command

The env command/printenv command displays only the Linux shell environment variables. What if you need to see a list of all variables, including shell, environment, user-defined shell functions? Try the following set command for printing environment variables:
set
set | grep BASH
Here is what we see:

The $PATH defined the search path for commands. It is a colon-separated list of directories in which the shell looks for commands. The $PS1 defines your prompt settings. See the list of all commonly used shell variables for more information. You can display the value of a variable using the printf command or echo command:

Outputs from the last command displaying my home directory location set by the $HOME environment variable on Linux:
/home/vivek

Источник

ИТ База знаний

Курс по 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 и технологией виртуализации в авторском мини — курсе от Михаила Якобсена

    Источник

    How To Read and Set Environmental and Shell Variables on Linux

    Last Validated on June 28, 2021 Originally Published on March 3, 2014

    Introduction

    When interacting with your server through a shell session, there are many pieces of information that your shell compiles to determine its behavior and access to resources. Some of these settings are contained within configuration settings and others are determined by user input.

    One way that the shell keeps track of all of these settings and details is through an area it maintains called the environment. The environment is an area that the shell builds every time that it starts a session that contains variables that define system properties.

    In this guide, we will discuss how to interact with the environment and read or set environmental and shell variables interactively and through configuration files.

    To follow along with this tutorial using a terminal in your browser, click the Launch an Interactive Terminal! button below:

    Otherwise if you’d like to follow along using your local system or a remote server, open a terminal and run the commands from this tutorial there.

    How the Environment and Environmental Variables Work

    Every time a shell session spawns, a process takes place to gather and compile information that should be available to the shell process and its child processes. It obtains the data for these settings from a variety of different files and settings on the system.

    The environment provides a medium through which the shell process can get or set settings and, in turn, pass these on to its child processes.

    The environment is implemented as strings that represent key-value pairs. If multiple values are passed, they are typically separated by colon ( : ) characters. Each pair will generally look something like this:

    If the value contains significant white-space, quotations are used:

    The keys in these scenarios are variables. They can be one of two types, environmental variables or shell variables.

    Environmental variables are variables that are defined for the current shell and are inherited by any child shells or processes. Environmental variables are used to pass information into processes that are spawned from the shell.

    Shell variables are variables that are contained exclusively within the shell in which they were set or defined. They are often used to keep track of ephemeral data, like the current working directory.

    By convention, these types of variables are usually defined using all capital letters. This helps users distinguish environmental variables within other contexts.

    Printing Shell and Environmental Variables

    Each shell session keeps track of its own shell and environmental variables. We can access these in a few different ways.

    We can see a list of all of our environmental variables by using the env or printenv commands. In their default state, they should function exactly the same:

    Your shell environment may have more or fewer variables set, with different values than the following output:

    This is fairly typical of the output of both printenv and env . The difference between the two commands is only apparent in their more specific functionality. For instance, with printenv , you can request the values of individual variables:

    On the other hand, env lets you modify the environment that programs run in by passing a set of variable definitions into a command like this:

    Since, as we learned above, child processes typically inherit the environmental variables of the parent process, this gives you the opportunity to override values or add additional variables for the child.

    As you can see from the output of our printenv command, there are quite a few environmental variables set up through our system files and processes without our input.

    These show the environmental variables, but how do we see shell variables?

    The set command can be used for this. If we type set without any additional parameters, we will get a list of all shell variables, environmental variables, local variables, and shell functions:

    This is usually a huge list. You probably want to pipe it into a pager program to more easily deal with the amount of output:

    The amount of additional information that we receive back is a bit overwhelming. We probably do not need to know all of the bash functions that are defined, for instance.

    We can clean up the output by specifying that set should operate in POSIX mode, which won’t print the shell functions. We can execute this in a sub-shell so that it does not change our current environment:

    This will list all of the environmental and shell variables that are defined.

    We can attempt to compare this output with the output of the env or printenv commands to try to get a list of only shell variables, but this will be imperfect due to the different ways that these commands output information:

    This will likely still include a few environmental variables, due to the fact that the set command outputs quoted values, while the printenv and env commands do not quote the values of strings.

    This should still give you a good idea of the environmental and shell variables that are set in your session.

    These variables are used for all sorts of things. They provide an alternative way of setting persistent values for the session between processes, without writing changes to a file.

    Common Environmental and Shell Variables

    Some environmental and shell variables are very useful and are referenced fairly often.
    Here are some common environmental variables that you will come across:

    • SHELL : This describes the shell that will be interpreting any commands you type in. In most cases, this will be bash by default, but other values can be set if you prefer other options.
    • TERM : This specifies the type of terminal to emulate when running the shell. Different hardware terminals can be emulated for different operating requirements. You usually won’t need to worry about this though.
    • USER : The current logged in user.
    • PWD : The current working directory.
    • OLDPWD : The previous working directory. This is kept by the shell in order to switch back to your previous directory by running cd — .
    • LS_COLORS : This defines color codes that are used to optionally add colored output to the ls command. This is used to distinguish different file types and provide more info to the user at a glance.
    • MAIL : The path to the current user’s mailbox.
    • PATH : A list of directories that the system will check when looking for commands. When a user types in a command, the system will check directories in this order for the executable.
    • LANG : The current language and localization settings, including character encoding.
    • HOME : The current user’s home directory.
    • _ : The most recent previously executed command.

    In addition to these environmental variables, some shell variables that you’ll often see are:

    • BASHOPTS : The list of options that were used when bash was executed. This can be useful for finding out if the shell environment will operate in the way you want it to.
    • BASH_VERSION : The version of bash being executed, in human-readable form.
    • BASH_VERSINFO : The version of bash, in machine-readable output.
    • COLUMNS : The number of columns wide that are being used to draw output on the screen.
    • DIRSTACK : The stack of directories that are available with the pushd and popd commands.
    • HISTFILESIZE : Number of lines of command history stored to a file.
    • HISTSIZE : Number of lines of command history allowed in memory.
    • HOSTNAME : The hostname of the computer at this time.
    • IFS : The internal field separator to separate input on the command line. By default, this is a space.
    • PS1 : The primary command prompt definition. This is used to define what your prompt looks like when you start a shell session. The PS2 is used to declare secondary prompts for when a command spans multiple lines.
    • SHELLOPTS : Shell options that can be set with the set option.
    • UID : The UID of the current user.

    Setting Shell and Environmental Variables

    To better understand the difference between shell and environmental variables, and to introduce the syntax for setting these variables, we will do a small demonstration.

    Creating Shell Variables

    We will begin by defining a shell variable within our current session. This is easy to accomplish; we only need to specify a name and a value. We’ll adhere to the convention of keeping all caps for the variable name, and set it to a simple string.

    Here, we’ve used quotations since the value of our variable contains a space. Furthermore, we’ve used single quotes because the exclamation point is a special character in the bash shell that normally expands to the bash history if it is not escaped or put into single quotes.

    We now have a shell variable. This variable is available in our current session, but will not be passed down to child processes.

    We can see this by grepping for our new variable within the set output:

    We can verify that this is not an environmental variable by trying the same thing with printenv :

    No output should be returned.

    Let’s take this as an opportunity to demonstrate a way of accessing the value of any shell or environmental variable.

    As you can see, reference the value of a variable by preceding it with a $ sign. The shell takes this to mean that it should substitute the value of the variable when it comes across this.

    So now we have a shell variable. It shouldn’t be passed on to any child processes. We can spawn a new bash shell from within our current one to demonstrate:

    If we type bash to spawn a child shell, and then try to access the contents of the variable, nothing will be returned. This is what we expected.

    Get back to our original shell by typing exit :

    Creating Environmental Variables

    Now, let’s turn our shell variable into an environmental variable. We can do this by exporting the variable. The command to do so is appropriately named:

    This will change our variable into an environmental variable. We can check this by checking our environmental listing again:

    This time, our variable shows up. Let’s try our experiment with our child shell again:

    Great! Our child shell has received the variable set by its parent. Before we exit this child shell, let’s try to export another variable. We can set environmental variables in a single step like this:

    Test that it’s exported as an environmental variable:

    Now, let’s exit back into our original shell:

    Let’s see if our new variable is available:

    Nothing is returned.

    This is because environmental variables are only passed to child processes. There isn’t a built-in way of setting environmental variables of the parent shell. This is good in most cases and prevents programs from affecting the operating environment from which they were called.

    The NEW_VAR variable was set as an environmental variable in our child shell. This variable would be available to itself and any of its child shells and processes. When we exited back into our main shell, that environment was destroyed.

    Demoting and Unsetting Variables

    We still have our TEST_VAR variable defined as an environmental variable. We can change it back into a shell variable by typing:

    It is no longer an environmental variable:

    However, it is still a shell variable:

    If we want to completely unset a variable, either shell or environmental, we can do so with the unset command:

    We can verify that it is no longer set:

    Nothing is returned because the variable has been unset.

    Setting Environmental Variables at Login

    We’ve already mentioned that many programs use environmental variables to decide the specifics of how to operate. We do not want to have to set important variables up every time we start a new shell session, and we have already seen how many variables are already set upon login, so how do we make and define variables automatically?

    This is actually a more complex problem than it initially seems, due to the numerous configuration files that the bash shell reads depending on how it is started.

    The Difference between Login, Non-Login, Interactive, and Non-Interactive Shell Sessions

    The bash shell reads different configuration files depending on how the session is started.

    One distinction between different sessions is whether the shell is being spawned as a login or non-login session.

    A login shell is a shell session that begins by authenticating the user. If you are signing into a terminal session or through SSH and authenticate, your shell session will be set as a login shell.

    If you start a new shell session from within your authenticated session, like we did by calling the bash command from the terminal, a non-login shell session is started. You were were not asked for your authentication details when you started your child shell.

    Another distinction that can be made is whether a shell session is interactive, or non-interactive.

    An interactive shell session is a shell session that is attached to a terminal. A non-interactive shell session is one is not attached to a terminal session.

    So each shell session is classified as either login or non-login and interactive or non-interactive.

    A normal session that begins with SSH is usually an interactive login shell. A script run from the command line is usually run in a non-interactive, non-login shell. A terminal session can be any combination of these two properties.

    Whether a shell session is classified as a login or non-login shell has implications on which files are read to initialize the shell session.

    A session started as a login session will read configuration details from the /etc/profile file first. It will then look for the first login shell configuration file in the user’s home directory to get user-specific configuration details.

    It reads the first file that it can find out of

    /.profile and does not read any further files.

    In contrast, a session defined as a non-login shell will read /etc/bash.bashrc and then the user-specific

    /.bashrc file to build its environment.

    Non-interactive shells read the environmental variable called BASH_ENV and read the file specified to define the new environment.

    Implementing Environmental Variables

    As you can see, there are a variety of different files that we would usually need to look at for placing our settings.

    This provides a lot of flexibility that can help in specific situations where we want certain settings in a login shell, and other settings in a non-login shell. However, most of the time we will want the same settings in both situations.

    Fortunately, most Linux distributions configure the login configuration files to source the non-login configuration files. This means that you can define environmental variables that you want in both inside the non-login configuration files. They will then be read in both scenarios.

    We will usually be setting user-specific environmental variables, and we usually will want our settings to be available in both login and non-login shells. This means that the place to define these variables is in the

    Open this file now:

    This will most likely contain quite a bit of data already. Most of the definitions here are for setting bash options, which are unrelated to environmental variables. You can set environmental variables just like you would from the command line:

    Any new environmental variables can be added anywhere in the

    /.bashrc file, as long as they aren’t placed in the middle of another command or for loop. We can then save and close the file. The next time you start a shell session, your environmental variable declaration will be read and passed on to the shell environment. You can force your current session to read the file now by typing:

    If you need to set system-wide variables, you may want to think about adding them to /etc/profile , /etc/bash.bashrc , or /etc/environment .

    Conclusion

    Environmental and shell variables are always present in your shell sessions and can be very useful. They are an interesting way for a parent process to set configuration details for its children, and are a way of setting options outside of files.

    This has many advantages in specific situations. For instance, some deployment mechanisms rely on environmental variables to configure authentication information. This is useful because it does not require keeping these in files that may be seen by outside parties.

    There are plenty of other, more mundane, but more common scenarios where you will need to read or alter the environment of your system. These tools and techniques should give you a good foundation for making these changes and using them correctly.

    Источник

    Читайте также:  Windows update code 80072ee2
  • Оцените статью