Linux export variable with dot

How to Set Environment Variables in Linux

Overview

In this tutorial, you will learn how to set environment variables in Ubuntu, CentOS, Red Hat, basically any Linux distribution for a single user and globally for all users. You will also learn how to list all environment variables and how to unset (clear) existing environment variables.

Environment variables are commonly used within the Bash shell. It is also a common means of configuring services and handling web application secrets.

It is not uncommon for environment specific information, such as endpoints and passwords, for example, to be stored as environment variables on a server. They are also used to set the important directory locations for many popular packages, such as JAVA_HOME for Java.

Setting an Environment Variable

To set an environment variable the export command is used. We give the variable a name, which is what is used to access it in shell scripts and configurations and then a value to hold whatever data is needed in the variable.

For example, to set the environment variable for the home directory of a manual OpenJDK 11 installation, we would use something similar to the following.

To output the value of the environment variable from the shell, we use the echo command and prepend the variable’s name with a dollar ($) sign.

And so long as the variable has a value it will be echoed out. If no value is set then an empty line will be displayed instead.

Unsetting an Environment Variable

To unset an environment variable, which removes its existence all together, we use the unset command. Simply replace the environment variable with an empty string will not remove it, and in most cases will likely cause problems with scripts or application expecting a valid value.

To following syntax is used to unset an environment variable

For example, to unset the JAVA_HOME environment variable, we would use the following command.

Listing All Set Environment Variables

To list all environment variables, we simply use the set command without any arguments.

An example of the output would look something similar to the following, which has been truncated for brevity.

Persisting Environment Variables for a User

When an environment variable is set from the shell using the export command, its existence ends when the user’s sessions ends. This is problematic when we need the variable to persist across sessions.

To make an environment persistent for a user’s environment, we export the variable from the user’s profile script.

  1. Open the current user’s profile into a text editor
  2. Add the export command for every environment variable you want to persist.
  3. Save your changes.

Adding the environment variable to a user’s bash profile alone will not export it automatically. However, the variable will be exported the next time the user logs in.

To immediately apply all changes to bash_profile, use the source command.

Export Environment Variable

Export is a built-in shell command for Bash that is used to export an environment variable to allow new child processes to inherit it.

To export a environment variable you run the export command while setting the variable.

We can view a complete list of exported environment variables by running the export command without any arguments.

To view all exported variables in the current shell you use the -p flag with export.

Setting Permanent Global Environment Variables for All Users

A permanent environment variable that persists after a reboot can be created by adding it to the default profile. This profile is loaded by all users on the system, including service accounts.

Читайте также:  Http с library linux

All global profile settings are stored under /etc/profile. And while this file can be edited directory, it is actually recommended to store global environment variables in a directory named /etc/profile.d, where you will find a list of files that are used to set environment variables for the entire system.

  1. Create a new file under /etc/profile.d to store the global environment variable(s). The name of the should be contextual so others may understand its purpose. For demonstrations, we will create a permanent environment variable for HTTP_PROXY.
  2. Open the default profile into a text editor.
  3. Add new lines to export the environment variables
  • Save your changes and exit the text editor
  • Conclusion

    This tutorial covered how to set and unset environment variables for all Linux distributions, from Debian to Red Hat. You also learned how to set environment variables for a single user, as well as all users.

    Источник

    Bash Export Variable

    By Alokananda Ghoshal

    Introduction to Bash Export Variable

    The following article provides an outline for Bash Export Variable. To start off, in case you are dabbed with other programming language, variables is something which will be quite familiar in your dictionary. For other who are not comfortable with other programming languages, a variable is a temporary placeholder to contain a number, a character or a string of characters. In bash specifically, one need not declare a variable, all we need to do is initialize or assign a value to the variable and in doing this, the variable will be created. Although these concepts are very easy to understand and use, a small deflection in understanding or their usage might make you land in a no mans land and coming out of that mess will be difficult. In other words, it is very easy and convincing to lead yourself into trouble if the understanding of the variables concept is no proper. Now before we see about what happens in the export command in bash, it is imperative to learn about how scripts work in bash.

    One more thing to keep in mind is that it is absolutely not necessary to fully know the underlying principles of running a script in order to actually write a script and run it successfully, but it becomes absolutely necessary when one starts getting into complex scripts, where one script is dependent on calling another script withing itself and keeps the interaction that way for execution. In this, we have concepts of programs and processes. Program is nothing but a combination of data which allows you to run series of instructions for the CPU and then process the binary output to human recognizable format to be presented. On the other hand, a process is basically running an instance of the binary set of instructions, referred to as program. One program might have several processes running separately, independent of each other.

    Web development, programming languages, Software testing & others

    For example, 2 different terminals running the same copy command is an exact example. Now when we run a bash script by executing bash , obviously once all the required permissions are provided for it to execute, the command will internally create a process. This process is like an instance where all the variable sin the script itself will be existing. Now, if in another process, may be internally run by the same script we have run, we would like to access the variables within the parent script, it will be not possible at all due to permissions and restriction in-built for a bash for security reasons. Now, in order to use a variable which is invariably the one that may not be reproduced anywhere else, we can export the variable from the parent script to use it in any of the child scripts.

    Читайте также:  Windows 10 256 ram

    Syntax for the export of variable:

    In our example we will also look at a live interpretation of how export is a one-way process. When we call an export, only the variable value gets exported to any of the other child processes that might be initiated. What doesn’t happen is that any change in the child process doesn’t affect the parent process. This concept comes in very handy incase one follows the methodical coding standards where a script might be broken down into smaller modular scripts and some variables needs to be exported in between the parent and corresponding child processes. For example, a small task in another big task is to create today’s dated file names form an existing directory.

    So, in the parent script, the list of files can be exported and, in the child process the task of prepending of today’s date is performed. One more point to keep in mind is that, by default all the variables which are defined in the scripts or are running within an instance are local. The -p option in export command helps in printing out all the variables which are getting exported. Also, -n option removes the export property from subsequent NAMEs. Also, by default environmental variables of parent script is exported to child processes.

    Example of Bash Export Variable

    Given below is the example mentioned:

    Code:

    #!/bin/bash
    echo «This is start of the parent process!»
    var_exp=»Initial Value Exp»
    var_noexp=»Initial Value Non»
    echo «Variable to be exported is:: $var_exp»
    echo » »
    echo «Variable not to be exported is:: $var_noexp»
    export var_exp
    bash childProcess.sh
    echo «Exported variable coming back after child process execution is:: $var_exp»
    echo » »
    echo «Non-Exported variable coming back after child process execution is:: $var_noexp»

    #!/bin/bash
    echo «This is start of the child process!»
    echo «Variable exported is:: $var_exp»
    echo » »
    echo «Variable not exported is:: $var_noexp»
    echo «Changing variable exported to child process to ‘Changed one Exp!’ to see its effect in the parent variable»
    echo «Changing variable not exported to child process to ‘Changed one No_Exp!’ to see its effect in the parent variable»
    var_exp=»Changed one Exp!»
    var_noexp=»Changed one No_Exp!»
    echo «Variable exported is changed to:: $var_exp in child process»
    echo » »
    echo «Variable not exported is changed to:: $var_noexp in child process»

    Источник

    Изучаем команды Linux: export

    1. Введение

    Export — это одна из встроенных команд оболочки bash, поэтому она является неотъемлемой частью вашей командной строки. Она очень проста в использовании, так как синтаксис export допускает использование всего трех опций командной строки. В целом команда export отмечает переменную окружения для экспорта с любым новым дочерним процессом, и это позволяет дочернему процессу наследовать все отмеченные переменные. В данной статье этот процесс будет описан более подробно.

    2. Часто используемые опции

    -p
    выводит список всех имен, экспортированных в текущей оболочке
    -n
    удаляет имена из списка экспорта
    -f
    имена экспортируются как функции

    3. Основы export

    Подумайте над следующим примером:

    Строка 1: создается новая переменная с именем «a», содержащая строку «linuxcareer.com».
    Строка 2: мы используем команду echo, чтобы вывести содержимое переменной «a».
    Строка 3: мы создаем дочерний экземпляр оболочки bash.
    Строка 4: переменная «a» теперь не определена.

    Из приведенного выше примера можно видеть, что любой дочерний процесс, ответвляющийся от родительского процесса, по умолчанию не наследует переменные родителя. Для этого и нужна команда export. Что произойдет, если мы используем команду export в вышеприведенном примере?

    Теперь в строке 3 мы использовали команду export, чтобы экспортировать переменную «a» в созданный новый дочерний процесс. В результате переменная «a» все еще содержит строку «linuxcareer.com», даже после создания нового экземпляра оболочки bash. Здесь важно отметить, что для успешного экспорта «a» необходимо, чтобы процесс, в который экспортируется переменная, ответвлялся от того родительского процесса, из которого экспортируется эта переменная. Связь между дочерним и родительским процессами описана ниже.

    Читайте также:  Залипает пуск windows 10

    4. Дочерние и родительские процессы

    В этом разделе мы коротко опишем взимосвязь между дочерним и родительским процессом. Все процессы могут быть родительскими и дочерними одновременно. Единственным исключением является процесс init, который всегда имеет PID (ID процесса) 1. Поэтому init является родительским для всех процессов, запущенных в системе Linux.

    Любой создаваемый процесс имеет родительский процесс, из которого он создается, и может быть определен как потомок этого родительского процесса. Например:

    Строка 1: вывести PID текущей командной оболочки — 27861
    Строка 2: создать новый дочерний процесс из процесса с ID 27861
    Строка 3: вывести PID текущей командной оболочки — 28034
    Строка 4: вывести список дочерних процессов для PID 27861 с помощью команды ps

    При создании нового дочернего процесса команда export просто обеспечивает, что все экспортируемые переменные родительского процесса доступны в дочернем процессе.

    5. Использование команды export

    Теперь, изучив основы, мы можем продолжить детальное исследование команды export. При использовании команды безо всяких опций и аргументов она просто выводит имена всех переменных, отмеченных для экспорта в дочерние процессы. То же самое происходит при использовании опции -p:

    Как было показано выше, для экспорта переменной мы просто используем имя переменной в качестве аргумента команды export.

    Как вы можете видеть, после экспорта переменной MYVAR, она будет показываться в списке экспортируемых переменных (строка 4). Приведенный выше пример можно сократить, используя команду export сразу при присваивании значения переменной.

    Наиболее широко команда export применяется для объявления переменной оболочки PATH:

    В этом примере мы включаем дополнительный путь /usr/local/bin в существующее определение PATH.

    6. Экспорт функций командной оболочки

    Используя опцию -f, команда export может быть также использована для экспорта функций. В примере ниже мы создаем функцию оболочки под именем printname, которая просто выводит строку «Linuxcareer.com» с помощью команды echo.

    7. Удаление имен из списка экспорта

    Выполнив один из вышеприведенных примеров, мы имеет переменную MYVAR, определенную в списке экспорта.

    Чтобы удалить переменную из списка экспорта, необходимо использовать опцию -n.

    8. Заключение

    В этой статье рассмотрены основы использования команды export. Чтобы узнать больше подробностей, используйте команду:

    Источник

    export command in Linux with Examples

    export is bash shell BUILTINS commands, which means it is part of the shell. It marks an environment variables to be exported to child-processes.

    Export is defined in POSIX as The shell shall give the export attribute to the variables corresponding to the specified names, which shall cause them to be in the environment of subsequently executed commands. If the name of a variable is followed by = word, then the value of that variable shall be set to the word.

    In simple terms, environment variables are set when you open a new shell session. at any time if you change any of the variable values, the shell has no way of picking that change. The export command, on the other hand, provides the ability to update the current shell session about the change you made to the exported variable. You don’t have to wait until new shell session to use the value of the variable you changed.

    Syntax :

    Options of export command

    1. Without any argument : To view all the exported variables.

    EXAMPLE :

    2. -p : To view all exported variables on current shell.

    SYNTAX :

    EXAMPLE :

    3. -f: It must be used if the names refer to functions. If -f is not used, the export will assume the names are variables.

    SYNTAX :

    EXAMPLE : To export shell function:

    Note: Bash command is used for showing that in the child shell, the shell function got exported.

    4. name[=value]: You can assign value before exporting using the following syntax.

    SYNTAX :

    EXAMPLE : To set vim as a text editor

    Note: No output will be seen on screen, to see exported variable grep from exported ones is used.

    5. -n: Named variables (or functions, with -f) will no longer be exported.

    SYNTAX :

    EXAMPLE :

    Note: No output will be seen on screen, to see exported variable grep from exported ones is used.

    Источник

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