Linux export all variables from file

Изучаем команды 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» необходимо, чтобы процесс, в который экспортируется переменная, ответвлялся от того родительского процесса, из которого экспортируется эта переменная. Связь между дочерним и родительским процессами описана ниже.

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 Explained

The export command in Linux is used for creating environment variables. You can use it like this:

or a shorthand like this to assign it a value immediately:

You can see the value of exported variables with the echo command:

To make the changes permanent, you should add it to the

That was just the quick summary. Let’s see it in details to understand it better.

Understanding how export command works

In the example below, I declare a shell variable var and assign it a value 3. It’s a shell variable for now.

If I exit the terminal and open a new terminal, this shell variable will disappear. If I want to use this variable in a shell script, it won’t work. Similarly, if I switch user (and thus initiating a new shell with this user), this shell variable won’t be available:

Now, let’s go back to the previous user (and thus the previous shell where I declared the shell variable). You can see that the variable still exists here (because we didn’t terminate this shell session yet):

So, now if I use the export command on the variable var here, it will become an environment variable and it will be available to all the subshells, users and shell scripts in this session.

You can check all the environment variables using the printenv command:

Make exported shell variables ‘permanent’ with bashrc file

But the struggle doesn’t end here. If you close the session, exit the terminal, log out or reboot your system, your environment variable will disappear again.

This is why it’s a common practice to add the export commands to the runtime configuration (rc) file of your shell.

Every shell has this rc file located in the user’s home directory which is used to determine variables and other configuration when the shell is started. As a user, you can use this rc file to customize your shell and its behavior.

If you are using bash shell, you should have a bashrc file at

/.bashrc. You can either edit this file in a text editor like Vim or you can just append export var=3 (or whatever you are exporting) to this file.

Once done, you should use the source command to make the changes available immediately.

A good practice is to keep all the user defined environment variables at one place.

Why use export command?

One of the most common use of the export command is when you want to add something to the path so that your Linux system will find the certain command/executable file.

For example, if you installed maven and you want to be able to run it, you should add the directory location of maven executables to the path like this:

What does it do? It adds this directory location to the path. When you try to run a command in Linux, your system searches for its executable (usually in bin directory) in the directories mentioned in the PATH variable.

Bonus Tip: Remove a variable from exported list

Suppose you want to remove an ‘exported’ variable. You can use the negate option in this fashion:

Keep in mind that this will not reset the value of the variable. It will just turn the exported global variable into a local variable. It will continue to have the same value you had set earlier.

Читайте также:  Как поменять герцовку монитора windows 10 amd

If you want to remove the variable from the exported list as well as remove its assigned value, use the unset option:

I hope you have a better idea of the export command in Linux now. If you have doubts, please feel free to ask in the comment section.

Источник

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.

Читайте также:  Celeron e3200 windows 10

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.

    Источник

    Linux Export Command Examples (How to Set Environment Variables)

    This article explains the basics of Linux export command and shows how to set, view and manipulate Linux env variables using export command.

    Environment variables in Linux are used by most of the activities taking place on a Linux system. From executing a standard command like ‘ls’ to installing a new software in your Linux box, each activity either uses or alters the environment variable list.

    Environment variable definition:

    Its a named object that can be used by multiple applications as it contains some valuable information required by these applications

    1. View all the Current Exported Variables

    Use export -p to view all the env variables as shown below. Partial output is shown here.

    Note that you can also see this list using the ‘env’ command.

    2. View a Specific Exported Variable

    Use echo command to display a specific environment variable. The following example displays the value of the PATH env variable.

    Also, refer to 15 Useful Bash Shell Built-in Commands, which explains about few other commands (e.g. env, unset, etc.) that also works on env variables.

    3. Set an Environment Variable

    You can add a new environment variable as shown below. The following creates a new environment variable called “MYAPP” and assigns the value of 1.

    Verify that the environment variable is set properly using the echo command.

    Note: Don’t give a space before and/or after = sign. For example, all of the following are invalid.

    4. Append a Value to an Environment Variable

    In the below example we try to append a new path to PATH variable. Use ‘:’ to separate the values.

    Verify that the value got appendd properly.

    5. Variables Without Export

    Assign a variable with a value in an interactive shell, and try to access the same in your shell script.

    Now, execute the above script as shown below.

    Still you will get blank value for variable MYAPP. The shell stores variable MYAPP with the LINUX only in the current shell. During the execution of myapp.sh, it spawns the shell and it executes the script. So the variable MYAPP will not have the value in the spawned shell. You need to export the variable for it to be inherited by another program – including a shell script.

    Also, refer to the bash variable tutorial, which explains local and global scope of variables, declaring a bash variable, and few other examples.

    6. Exporting Variables Permanently

    To export variables permanently, you can add the export command in any of the following start-up files :

    There could be some limitations like ”

    /.profile is not read by bash, if

    /.bash_login exists.”. So one should read the ‘/usr/share/doc/bash/examples/startup-files’ to get a better idea of how these start-up files work.

    It is also important to understand the execution sequence of .bash_profile, .bashrc, .bash_login, .profile and .bash_logout, which will help you to decide which file to use to set your environment variable for your specific situation.

    Источник

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