Linux what is export command

Изучаем команды 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.

Читайте также:  Windows 10 можно ли установить офис

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

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

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

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

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

Источник

Use export Command in Linux / Unix

Syntax

The syntax is as follows:[donotprint]

Tutorial details
Difficulty level Easy
Root privileges No
Requirements None
Est. reading time 1m

[/donotprint]

You can assign value before exporting using the following syntax:
export VAR=value

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

VAR=value
export VAR

The export command will marks each VAR for automatic export to the environment of subsequently executed commands i.e. make the local shell variable VAR global.

Examples

To make the local shell variable called PATH type the following:

Set a new EDITOR variable:

You need to add export statements to

/.profile or /etc/profile file. This will export variables permanently:
$ vi

/.bash_profile
Sample file

To see all a list of all exported variables and functions, enter:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

Could you comment on the following unexpected (to me) behavior of the export command in bash and dash. Note the punctuation or lack thereof.
($ = prompt, # = output)

standard/normal cases:
$ echo -$bar -$foo
# – –
$ export bar=foo; echo -$bar
# -foo
$ echo -$bar
# -foo
$ bar=fu; export bar; echo -$bar
# -fu
$ echo -$bar
# -fu
$ bar=foo; echo -$bar
# -foo
$ echo -$bar
# -foo

And now for something different:
$ foo=bar echo -$foo
# –
$ foo\=bar ; echo -$foo
# fu=bar: command not found
# –
$ echo -$foo
# –
$ foo=bar export foo; echo -$foo
# -bar
$ foo=bear; export foo; echo -$foo
# -bear
$ `foo=bar` echo -$foo
# -bar

My question is basically, why does the shell appear to be automatically expanding a variable assignment (or “silently executing an assignment”) prior to an export, but not prior to another command like echo? Is export “special”? What other circumstances have behavior like export?

The reason this came up is because I’ve seen a couple of example scripts that have a line similar to
/bin/sh -c ‘DISPLAY=:0 some_GUI_program’
Should this do anything in general? If so, why?

(I’ve been using linux on and off for about 15 years now, including at one point administering a production linux box, but still feel like a complete n00b)

in samples file

“# set vim as a text editor
export EDITOR=/usr/bin/bin”

you mean /usr/bin/vim

Thanks for the heads up!

Hi,
Am porting my code base to run with a different toolchain. This new toolchain has the standard libraries defined in /usr/. When I export this path as “export PATH=$PATH:/usr/bin”, this path is added to the existing variable PATH. The output looked like,
declare -x PATH=”/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/bin”
So my understanding is that, the compiler still searches in /usr/local/sbin or /usr/local/bin first and uses libraries from there.
But I want my compiler to look into toolchain_path for all standard libraries.
How do I achieve it.
Thanks,
Bhargavi

Simply swap it round to “export PATH=/usr/bin:$PATH”

But if you’re specifically talking about the *compiler* search path, rather than the *shell* search path, then this is something different and you’ll have to check your compiler’s manual.

Источник

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.

Источник

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.

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.

Источник

Читайте также:  Linux bash read примеры
Оцените статью