Environment Variables in Linux. PATH environment variable How to add program to path linux

What it is? Many of the commands you enter at the command line require the use of an external program loaded from the file system. For example, commands like mkdir and wc are actually in the /bin folder.

When you enter a statement that the Bash shell doesn't recognize, it tries to execute it as a program and returns an error if it doesn't find a program with that name. And this applies not only to the basic commands that we considered, because from command line you can run any program.


But how does Linux know which programs to run from which directories, given the presence in the file system? The OS uses the system environment variable to specify a subset of folders to look in when receiving an unknown command. This variable is called PATH and can be displayed with the following echo command (the $ symbol is required):

echo $PATH

The output of this command will look like the following seven absolute folder paths, separated by colons:

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

Each time you enter an unknown command, Linux will look through each of the folders specified in the environment variable, in the order they were specified, looking for a program with the same name. If the program is found, it is launched; otherwise, an error message is displayed. But it will not be a mistake if you buy your beloved silver rings as a gift. Silver will adorn any woman!

These seven folders provide easy access to all major programs in the operating system, including . Any programs outside of these seven folders cannot be launched by simply typing their name on the command line.

For example, you downloaded the diary utility from the Internet to your home folder. If you enter its name on the command line, you will get an error because it is located in a folder that is not included in the system path. To run this program, enter the following line (remember that the ~ symbol is shorthand for your home folder):

If you saved it to a folder outside of your specified path, you will need to enter the absolute path and filename to run the utility.

Of course, diary is assumed to be a simple standalone program that doesn't require installation, because most major applications will place the program's executable somewhere in your specified path during the installation process. Like this PATH environment variable, enjoy your health!

Environment variables ( environment variable) are used to store common values ​​of variables across scripts and programs. Such variables can be set for a period of time, for example, for the period of operation of a specific terminal shell, or for the period of a user session, or you can set an environment variable at the global level - for the entire system.

Environment variables

$HOME
The variable contains the path to the current user's home directory. $USER
Current username $PATH
List of directories for the shell to search for executable programs. $PWD
The path to the current working directory (or pwd). Example: dir_path=$(pwd) . $SHELL
Default interpreter $RANDOM
Generates a random number 0..32767 each time the variable is accessed. $SECONDS
Time in sec. since the start of the shell. $? The result of the previous command. $HOSTNAME
Computer name $HISTFILE
Path to $IFS interpreter history file
List of separator characters for commands, parameters, array elements (default: space, tab, newline) $PS1
Interpreter prompt string template.

Temporarily setting an environment variable

Setting an environment variable for the session period:

# For a new process env varname=value [command] # For the current shell and all its subprocesses export varname=value [command]

The value of the variable is retained until the system is rebooted.

Setting a constant value

System-level environment variables are set via the /etc/environment file:

ENVIRONMENT="dev"

Setting a user-specific environment variable via ~/.bashrc or ~/.bash_profile:

PATH="$(PATH):/home/user/bin:"

Attention!

The file ~/.bash_profile will be executed when the interpreter is started with the -l switch. When logged in locally, this file is not readable!

You also need to remember that the changes will take effect only after the session is restarted!

Viewing the value of an environment variable

To view the value of an environment variable, use the printenv command:

Printenv<имя_переменной>

#shell, #bash, #environment

The AIR SDK contains several programs that you can run from the command line or a terminal window. Running these programs is much more convenient if you define the path to the SDK's bin directory using the Path environment variable.

This section provides a general description of the procedure for setting the path on Windows, Mac, and Linux. However, computer configurations can vary greatly, so this procedure may not work on all systems. In this case, the information you need can be found in the operating system documentation or on the Internet.

Setting the PATH environment variable on Linux and Mac OS using the Bash shell

When a command is entered into a terminal window, the shell (the program that reads the commands being entered and tries to respond appropriately) must first find the command's program in the file system. The shell searches for commands in a list of directories, which is stored in an environment variable named $PATH. To view the current value of the path variable, type the following command:

echo $PATH

A colon-separated list of directories will be displayed, something like this:

/usr/bin:/bin:/usr/sbin:/usr/local/bin:/usr/x11/bin

The path to the AIR SDK bin directory must be added to this list so that the shell can find the ADT and ADT tools. Let's say the AIR SDK is in the /Users/fred/SDKs/AIR directory. In this case, the following command is used to add the required directories to the path environment variable:

Export PATH=$PATH:/Users/fred/SDKs/AIR/bin:/Users/fred/SDKs/android/tools

Note. If the path contains whitespace characters, they must be preceded by a backslash character, as shown below:

/Users/fred\ jones/SDKs/AIR\ 2.5\ SDKs/bin

To check the results of adding, you can run the echo command again:

Echo $PATH /usr/bin:/bin:/usr/sbin:/usr/local/bin:/usr/x11/bin:/Users/fred/SDKs/AIR/bin:/Users/fred/SDKs/android/ tools

Directories added successfully. Now you can call the following commands and get the correct response:

Adt-version

If the $PATH environment variable was changed correctly, the command should output the ADT environment version.

However, there is one problem: when you open a new terminal window, you will notice that the path variable no longer contains the new elements that were previously added to it. The path setting command must be run every time you start a new terminal.

A common solution to this problem would be to add the command to one of the startup scripts that the shell uses. On Mac OS, you can create a .bash_profile file in the ~/username directory that will run every time you open a new terminal window. In Ubuntu, the script that is run when a new terminal window is opened is .bashrc. In others Linux distributions and shells, similar rules apply.

Procedure for adding a command to a shell startup script

    Change your home directory:

    Create a shell configuration profile (if necessary) and redirect the input text to the end of the file using the cat >> command. Use the appropriate file for your operating system and shells. For example, you can use .bash_profile on Mac OS and .bashrc on Ubuntu.

    Cat >> .bash_profile

    Enter the text you want to add to the file:

    Export PATH=$PATH:/Users/cward/SDKs/android/tools:/Users/cward/SDKs/AIR/bin

    End the text redirection by pressing the CTRL-SHIFT-D keys on your keyboard.

    Display the file to verify that the operation was performed correctly:

    Cat .bash_profile

    Open a new terminal window to check the path:

    echo $PATH

    The added elements should be displayed on the screen.

If later created a new version one of the SDKs to be placed in a different directory, the path setting command in the configuration file will need to be updated accordingly. Otherwise, the shell will continue to use the old version.

Setting the PATH environment variable on Windows

When a command window is opened on Windows, it inherits the global environment variables defined in the system properties. One important variable is the path variable, which contains a list of directories in which to search for the entered program. To view the current list of directories in the path variable, you can type the following command in the command window:

set path

This will output a colon-separated list of directories that looks something like this:

Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem

The path to the AIR SDK bin directory must be added to this list so that the command program can find the ADT and the ADT tools. Assume that the AIR SDK is located in the C:\SDKs\AIR directory. In this case, the path can be added like this:

    In the Control Panel section, open the System Properties dialog box or right-click on the My Computer icon and select Properties from the menu.

    On the Advanced tab, click the Environment Variables button.

    In the System Variables section of the Environment Variables dialog box, select the Path element.

    Click the Change button.

    Move to the end of the line in the Variable Value field.

    At the very end of the current value, enter the following text:

    ;C:\SDKs\AIR\bin

    Press the "OK" button in all dialog boxes to save the path.

If there are command windows open at this point, the changes to them will not be applied. Open a new command window and type the following command to make sure the environment variable is set correctly:

Adt-version

If the location of the AIR SDK is later changed or a new version is added, the path environment variable will need to be changed accordingly.

I'm wondering where the new path should be added to the PATH environment variable. I know this can be done by editing .bashrc (for example), but it's not clear how.

Thus:

Export PATH=~/opt/bin:$PATH

Export PATH=$PATH:~/opt/bin

11 responses

simple material

PATH=$PATH:~/opt/bin PATH=~/opt/bin:$PATH

depending on whether you want to add ~/opt/bin at the end (to search all other directories if there is a program with the same name in multiple directories) or at the beginning (to search before all other directories).

You can add multiple entries at the same time. PATH=$PATH:~/opt/bin:~/opt/node/bin or changes in collation just fine.

You don't need to export if the variable is already in the environment: any change to the variable's value is reflected in the environment.¹ PATH is pretty much always in the environment; All unix systems install it very early (usually in the very first process, in fact).

If your PATH is created by many different components, you may end up with duplicate entries. See How to add a home directory path that will be discovered by Unix, which command? and Remove duplicate $PATH entries with awk command to avoid duplication or remove them.

Where to put

Note that ~/.bash_rc is not readable by any program, and ~/.bashrc is a configuration file for interactive bash instances. You should not define environment variables in ~/.bashrc . The correct place to define environment variables such as PATH is ~/.profile (or ~/.bash_profile if you don't like shells other than bash). See What is the difference between them and which one should I use?

Notes on non-bash shells

In bash, ksh and zsh, export is a special syntax, and both PATH=~/opt/bin:$PATH and export PATH=~/opt/bin:$PATH do the right thing even. In other Bourne/POSIX shells, such as dash (which is /bin/sh on many systems), export is parsed as a normal command, which implies two differences:

  • ~ is only parsed at the beginning of a word, except for assignments (see How do I add a path to a home directory that will be discovered by Unix that requires a command? ;
  • $PATH outer double quotes breaks if PATH contains spaces or \[*? .

So, in shells like dash, export PATH=~/opt/bin:$PATH sets PATH to the literal string ~/opt/bin/: followed by the value of PATH up to the first place. PATH=~/opt/bin:$PATH (simple assignment) doesn't require quotes and does the right thing. If you want to use export in a portable script, you need to write export PATH="$HOME/opt/bin:$PATH" or PATH=~/opt/bin:$PATH export PATH (or PATH=$HOME/opt/bin: $PATH export PATH for portability even to the Bourne shell, which doesn't accept export var=value and didn't do tilde expansion).

¹ This was not true in Bourne shells (like the actual Bourne shell, not modern POSIX-style shells), but you're not likely to run into those old shells these days. Sub>

Either way works, but they don't do the same thing: PATH elements are checked from left to right. In the first example executable files in ~/opt/bin will take precedence over those set in /usr/bin for example, which may or may not be what you want.

In particular, it's dangerous from a security point of view to add paths to the front, because if someone can get write access to your ~/opt/bin , they can put another ls for example, which you'll probably use instead /bin/ls without noticing. Now imagine doing the same for ssh or your browser or choice... (Three times put the same on your path.)

I'm confused about question 2 (since it's removed from the question since it was related to an unrelated issue):

What effective method adding additional paths to different lines? Initially I thought this might do the trick:

export PATH=$PATH:~/opt/bin export PATH=$PATH:~/opt/node/bin

But that's not because the second assignment not only adds ~/opt/node/bin , but also the previously assigned PATH .

This is a possible workaround:

Export PATH=$PATH:~/opt/bin:~/opt/node/bin

But for readability, I'd rather have one destination per path.

If you say

PATH=~/opt/bin

This all, which will be in your PATH. PATH is just an environment variable and if you want to add to PATH you need to rebuild the variable with exactly the content you want. That is, what you give as an example to question 2 is exactly what you want to do, if I haven't completely missed the point of the question.

I use both forms in my code. I have a generic profile that I install on every machine I work on that looks like this to host potentially missing directories:

Export PATH=/opt/bin:/usr/local/bin:/usr/contrib/bin:/bin:/usr/bin:/usr/sbin:/usr/bin/X11 # add optional items to the path for bindir in $HOME/local/bin $HOME/bin; do if [ -d $bindir ]; then PATH=$PATH:$(bindir) fi done

Linux defines an executable search path with the $PATH environment variable. To add the /data/myscripts directory to the beginning of the $PATH environment variable, use the following:

PATH=/data/myscripts:$PATH

To add this directory to the end of the path, use the following command:

PATH=$PATH:/data/myscripts

But the previous ones are not enough, because when you set an environment variable inside a script, that change only takes effect inside the script. This limitation is limited in two ways:

  • If you export an environment variable inside a script, it is effective within any program called by the script. Note that this is not effective in the program that called the script.
  • If the program calling the script does so by including instead of calling, any environment changes in the script are effective in the calling program. This inclusion can be done with the dot command or the source command.

$HOME/myscript.sh source $HOME/myscript.sh

Inclusion basically includes the "invoked" script in the "invoking" script. This is similar to #include in C. Thus, it is effective inside a script or calling program. But of course this is not effective for any programs or scripts called by the calling program. To make it effective up to the call chain, you must follow the setting of the environment variable with the export command.

As an example, the bash shell program includes the contents of the .bash_profile file upon inclusion. So put the following 2 lines in .bash_profile:

PATH=$PATH:/data/myscripts export PATH

effectively puts those 2 lines of code into a bash program. Thus, in bash variable$PATH includes $HOME/myscript.sh , and because of the export statement, any programs called by bash have their $PATH variable changed. And since any programs you run from a bash prompt are called by bash, the new path applies to anything you run from a bash prompt.

The bottom line is that in order to add a new directory to the path, you need to add or prepend the directory to the $PATH environment variable in a script included with the shell, and you must export the $PATH environment variable.

For some time now, I've kept with me the two functions pathadd and pathrm , which help you add elements to a path without worrying about duplications.

pathadd takes one path argument and an optional after argument which, if added, will be added to PATH , otherwise it will add it.

In any situation, if you're adding a path, you probably want to override whatever's already in the path, which is why I prefer to add the default.

Pathadd() ( newelement=$(1%/) if [ -d "$1" ] && ! echo $PATH | grep -E -q "(^|:)$newelement($|:)" ; then if [ " $2" = "after" ] ; then PATH="$PATH:$newelement" else PATH="$newelement:$PATH" fi fi ) pathrm() ( PATH="$(echo $PATH | sed -e "s; \(^\|:\)$(1%/)\(:\|\$\);\1\2;g" -e "s;^:\|:$;;g" -e "s ;::;:;g")" )

Put them in any script you want to change the PATH environment and now you are good to go.

pathadd "/foo/bar" pathadd "/baz/bat" after export PATH

You are guaranteed not to add the path if it already exists. If you want /baz/bat to be started at the beginning.

Pathrm "/baz/bat" pathadd "/baz/bat" export PATH

Now any path can be moved to the front if it is already on the path without doubling it.

Bulletproof way to add/pre-treat

There are many considerations involved in the choice of add and add. Many of these are covered in other answers, so I won't repeat them here.

The important point is that even if system scripts don't use this (I wonder why) * 1 , a bulletproof way to add a path (e.g. $HOME/bin) to the PATH environment variable

PATH="$(PATH:+$(PATH):)$HOME/bin"

to add (instead of PATH="$PATH:$HOME/bin") and

PATH="$HOME/bin$(PATH:+:$(PATH))"

to add (instead of PATH="$HOME/bin:$PATH")

This avoids a false leading/trailing colon when $PATH is initially empty, which can have unwanted side effects and can be a nightmare to find elusively (this answer briefly addresses the awk-way case).

$(parameter:+word)

If parameter is null or unset, nothing is replaced, otherwise word is replaced.

So $(PATH:+$(PATH):) expands to: 1) nothing if PATH is null or unset, 2) $(PATH): if PATH is set.

Note. This is for bash.

*1 I just found that scripts like devtoolset-6/enable actually use this $ cat /opt/rh/devtoolset-6/enable # General environment variables export PATH=/opt/rh/devtoolset-6/root/usr /bin$(PATH:+:$(PATH)) ...

I can't speak for other distributions, but Ubuntu has a file /etc/environment which is the default search path for all users. Since my computer is only used by me, I put whatever directories I want on my path there, unless it's a temporary addition I put into the script.

For me (on Mac OS X 10.9.5) adding a pathname (e.g. /mypathname) to the /etc/paths file worked just fine.

Before editing, echo $PATH is returned:

/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin

After editing /etc/paths and restarting the shell, the $PATH variable is added with /pathname . Indeed, echo $PATH returns:

/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/mypathname

It happened that /mypathname was added to the $PATH variable.

Environment variables in Linux are special variables defined by the shell and used by programs during execution. They can be defined by the system and the user. Linux system environment variables are defined by the system and used by system-level programs.

For example, the PWD command uses a system variable to keep the old working directory. User environment variables are set by the user, for the current shell, temporarily or permanently. The whole concept of adding and removing shell variables revolves around multiple files, commands, and various shells.

More broadly, an environment variable can be of three types:

1. Local environment variables

These variables are only defined for the current session. They will be permanently erased after the end of the session, whether remote access or a terminal emulator. They are not stored in any files, but are created and deleted using special commands.

2. User Shell Variables

These Linux shell variables are defined for a specific user and are loaded each time the user logs in using a local terminal, or connects remotely. Such variables are usually stored in configuration files: .bashrc, .bash_profile, .bash_login, .profile, or other files located in the user's directory.

3. System environment variables

These variables are available throughout the system, for all users. They are loaded at system startup from system configuration files: /etc/environment, /etc/profile, /etc/profile.d/ /etc/bash.bashrc.

Linux environment variable configuration files

Here, we'll take a quick look at the various configuration files listed above, which are used to set environment variables for the entire system or a specific user.

.bashrc

This is a user specific variable file. It is loaded every time the user creates a terminal session, that is, in other words, opens a new terminal. All environment variables created in this file take effect every time a new terminal session is started.

.bash_profile

These variables take effect every time a user connects remotely via SSH. If this file is missing the system will look for .bash_login or .profile.

/etc/environment

This file is for creating, editing and deleting any environment variables at the system level. Environment variables created in this file are available for the entire system, for each user, and even when connected remotely.

/etc/bash.bashrc

System bashrc. This file is executed for each user, every time he creates a new terminal session. This only works for local users, when connected via the Internet, such variables will not be visible.

/etc/profile

The system file profile. All variables in this file are available to any user on the system only if they are logged in remotely. But they won't be available when creating a local terminal session, i.e. if you just open a terminal.

All Linux environment variables created with these files can be removed by simply deleting them from there. Only after each change, you need to either log out and log in, or run this command:

source filename

Adding User and System Environment Variables in Linux

Now that you know a little theory, let's move on to practice. Local environment variables in Linux can be created with the following commands:

var=value
$ export var=value

These variables will only be available for the current terminal session.

Several commands can be used to remove environment variables:

1. Using env

By default, env can be used to view all set environment variables. But with the -i option, it allows you to temporarily remove all shell variables and run the command without variables.

env -i command

Var is any variable you want to pass to this command.

This command will start a shell without environment variables at all:

After starting such an environment, no variables will be available, but after exiting everything will return to their places.

2. Using unset

This is another way to remove Linux environment variables. Unset removes a variable by name until the end of the current session:

unset variable_name

3. Set variable value to ""

This is the easiest way to delete environment variables in Linux, by setting a variable to empty you delete it for the rest of the current session.

Note: Using these methods, you can change the values ​​of system or user variables, but they will only be relevant for the current session.

Creating User and System Environment Variables

In this section, we will look at how to set and remove system and user variables not only for the current session, but so that the effect persists after a reboot.

1. Set and remove local variables in Linux

Let's create a local variable VAR and set it to any value, then remove it with unset and make sure it's removed:

VAR1="Loss"
$ echo $VAR1
$ unset VAR1
$ echo $VAR1

Another way to create a variable is with the export command. Remove it by assigning an empty value:

export VAR="Loss"
$ echo $VAR
$var=
$ echo $VAR

Now let's create a variable VAR2 and give it a value. And then temporarily remove all local variables by running env -i. It will start the shell without any variables. After typing exit, all variables will be restored.

VAR2="Loss"
$ echo $VAR2
$ env -i bash
$ echo $VAR2

Setting and Removing User Variables

Edit the .bashrc file in your home directory by adding an export command to export the desired variable. Then run the source command to apply the changes. Let's create, for example, a CD variable:

Add this line (o, then paste, then Esc and :wq):

export CD="This is Lost Home"

Now it remains to update the configuration:

source .bashrc
$ echo $CD

To remove this variable, simply remove it from .bashrc.

Now let's add an environment variable with .bash_profile. This variable, as you already know, will only be available when you log in remotely:

vi .bash_profile

Add a line:

export VAR2="This is Lost Home"

And run these commands to apply the changes and test the variable addition:

source .bash_profile
$ echo $VAR2

The variable is not available because you have created a local terminal session, now connect via ssh:

ssh [email protected]
$ echo $VAR2

You can delete this environment variable in the same way as in the previous case by deleting it from the file.

Comment: These variables are always available, but not for all users.

Setting and removing system environment variables

Let's create a variable available to all users in all terminal sessions except remote ones by adding it to /etc/bash.profile:

vi /etc/bash.profile

export VAR="This is a system-wide variable"

Then we update:

source /etc/bash.bashrc

Now this variable is available to all users, in all terminals:

echo $VAR
$ sudo su
$ echo $VAR
$su-
$ echo $VAR

If you want to make the environment variable available to all users who connect to this machine remotely, edit the /etc/profile file:

export VAR1="This is a system-wide variable for only remote sessions"

Update the configuration, and check the availability of the variable, it will only be available remotely:

source /etc/profile
$ echo $VAR1

If you need to add an environment variable on Linux so that it is available to both remote and local sessions, export it to /etc/environment:

vi /etc/environment

export VAR12="I am available everywhere"

We check:

source /etc/environment
$ echo $VAR12
$ sudo su
$ echo $VAR12
$exit
$ ssh localhost
$ echo $VAR12

mob_info