M. Garrels. bash manual

2.2. Environment Variables

The operating system maintains a special kind of resource called Environment Variables (environment variables). These variables are a pair NAME - VALUE . The name can start with a letter and consist of letters, numbers, and underscores.

To substitute the value of a variable on the command line, the variable name is preceded by a $ sign:

$ echo $USER guest

If the variable is not set, an empty string is returned.

An assignment statement is used to set the value of a variable (in the case of Bourne-like shells):

$ TEST=test

or the built-in set statement (in the case of C-likes):

$ set TEST=test

The set command without arguments lists the values ​​of all variables set in the environment:

$ set COLUMNS=197 CVS_RSH=ssh DIRSTACK=() EUID=1000 GROUPS=() G_BROKEN_FILENAMES=1 HISTFILE=/home/guest/.bash_history HISTFILESIZE=1000 HISTSIZE=1000 HOME=/home/guest HOSTNAME=myhost HOSTTYPE=i686 IFS =$" \t\n" INPUTRC=/etc/inputrc KDEDIR=/usr KDEDIRS=/home/guest/.local/ KDE_IS_PRELINKED=1 KDE_NO_IPV6=1 LANG=ru_RU.UTF-8 LESSOPEN="|/usr/bin/ lesspipe.sh %s" LINES=65 LOGNAME=guest ....

Variables can be local to a given process or global to a session. You can set local values ​​for variables by preceding them with commands:

$ TEST=test1 sh -c "echo $TEST" test1

You can evaluate the contents of a set of variables for a session by calling the built-in command of the env interpreter, in the case of Bourne-like interpreters (sh, ksh, bash, zsh, pdksh...), and printenv in the case of using C-Shell clone interpreters (csh, tcsh. ..):

$ env HOSTNAME=myhost TERM=xterm SHELL=/bin/bash HISTSIZE=1000 KDE_NO_IPV6=1 SSH_CLIENT=172.16.0.9 50487 22 QTDIR=/usr/lib/qt-3.3 QTINC=/usr/lib/qt-3.3/include SSH_TTY =/dev/pts/6 USER=guest MOZILLA_CERTIFICATE_FOLDER=/home/guest/.evolution/ KDEDIR=/usr MAIL=/var/spool/mail/guest PATH=/usr/games:/usr/local/bin:/bin :/usr/bin:/home/guest/bin INPUTRC=/etc/inputrc PWD=/home/guest KDE_IS_PRELINKED=1 LANG=ru_RU.UTF-8 KDEDIRS=/home/guest/.local/ SSH_ASKPASS=/usr/libexec /openssh/gnome-ssh-askpass SHLVL=1 HOME=/home/guest LOGNAME=guest QTLIB=/usr/lib/qt-3.3/lib CVS_RSH=ssh SSH_CONNECTION=172.16.0.9 50487 172.16.2.9 22 LESSOPEN=|/usr /bin/lesspipe.sh %s G_BROKEN_FILENAMES=1 _=/bin/env

Command sets Shell can be linked into batch files called scripts, where the first line in a special kind of comment indicates the command interpreter for executing this set. For example, let's create a file in a text editor called test , with the following content:

#!/bin/sh echo TEST variable: echo $TEST

This program will output standard output the text message "Variable TEST: " and the value of the variable TEST, if it is set. Run it from command line You can by passing it as a parameter to the shell:

$ sh test Variable TEST:

You can make a variable global using the export (Bourne) or setenv (C-SHell) statement:

$ export TEST=test1 $ sh test Variable TEST: test1

You can set local values ​​of variables for the execution of this program by preceding them with commands:

$ TEST=test2 sh test Variable TEST: test2

Environment variables are removed using the unset statement.

Environment variables are special variables that are defined in the shell and are needed by programs or scripts at run time. They can be defined by the system or by the user. System-defined variables are those that are set by the system.

For example command PWD is a very common system variable that is used to store the current working directory. User variables are usually set either temporarily for the current shell or permanently. The whole concept of configuring and changing environment settings revolves around a set of files and a few commands and different shells.

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

1. Local environment variable

It is defined for the current session. These environment variables are used for the duration of the current session, whether it is a remote login session or a local terminal session. These variables are not specified in any configuration files and are created and removed using a special set of commands.

2. User environment variable

These are user-specific variables that are loaded each time the user logs in using a local terminal session or if that user logs in using a remote login session. These variables are usually set and loaded from the following configuration files: .bashrc,.bash_profile,.bash_login,.profile, which are present in the user's home directory.

3. System environment variables

These are environment variables that are available system-wide, that is, for all users present on that system. These variables are present in the system-wide configuration files found in the following directories and files: /etc/environment,/etc/profile, /etc/profile.d/, /etc/bash.bashrc. These variables are loaded each time the system is turned on and users log in, either locally or remotely.

Understanding Shared and System-Wide Configuration Files

Here we will briefly describe the various configuration files listed above that contain environment variables, both system and user.

.bashrc

This file is a user file that is loaded every time the user creates a new local session, i.e. in simple words, opens a new terminal. All environment variables created in this file take effect each time a new local session is started.

.bash_profile

The environment variables listed in this file are called each time a user logs in remotely, i.e. with the command ssh. If this file does not exist, the system looks for files .bash_login or .profile.

/etc/environment

This file is a system file for creating, editing or deleting any environment variables. The environment variables created in this file are available throughout the system, to every user globally, both locally and remotely.

/etc/bash.bashrc

System file bashrc. This file is downloaded once per user, each time the user opens a local terminal session. Environment variables created in this file are available to all users, but only through a local terminal session. When any user on this computer is deleted via a remote login session, these variables will not be visible.

/etc/profile

All variables created in this file are available to every user on the system, but only if that user session is invoked remotely, that is, via remote login. Any variable in this file will not be available to the local login session, i.e. when the user opens a new terminal on their local system.

Note. Environment variables created using system-wide or user-defined configuration files can be deleted, but you can only do so from those files. Just after each change to these files, either log out or log in again or just type the following command on the terminal for the changes to take effect:

$ source

Setting or removing local or session environment variables in Linux

Local environment variables can be created using the following commands:

$ var=value OR $ export var=value

These variables are session variables and are valid only for the current terminal session. To clear these environment variables, you can use the following commands:

1. Usage env

The default command is " env» lists all current environment variables. But, if used with the key " -i”, then it temporarily clears all environment variables and allows the user to run the command in the current session in the absence of all environment variables.

$ env -i ... command args ...

Here var = value matches any local environment variable you want to use with this command only.

$ env -i bash

We start the bash shell, in which all environment variables will be temporarily cleared. But when you exit the shell, all variables will be restored.

2. Using Cancel

Another way to clear a local environment variable is to use the command unset. To temporarily disable any local environment variable,

$unset

Where, var-name is the name of the local variable you want to delete or clear.

3. Set the variable name with empty value

Another less popular way is to set the name of the variable you want to clear to an empty value, i.e. VAR=(there is nothing after equals - press enter). This will clear the value of the local variable for the current session for which it is active.

NOTE. YOU CAN DO CHANGE THE SYSTEM VARIABLES, BUT THE CHANGES WILL ONLY BE REFLECTED IN THE CURRENT SESSION AND WILL NOT BE PERMANENT.

Learn How to Create, User and System Environment Variables in Linux

In this section, we will look at how to set or disable local, user and system environment variables in Linux with the examples below:

1. Setting and removing local variables in Linux.

a) Here we create a local variable VAR1 and set it to any value. We then use unset and at the end we delete this variable.

$ VAR1="TecMint is best Site for Linux Articles" $ echo $VAR1 $ unset VAR1 $ echo $VAR1

b) Another way to create a local variable is to use the command export. The created local variable will be available for the current session. To disable a variable, simply set the variable to an empty value.

$ export VAR="TecMint is best Site for Linux Articles" $ echo $VAR $ VAR= $ echo $VAR

c) Here we have created a local variable VAR2 and set its value. Then, to run the command, temporarily clearing all local and other environment variables, we ran the command " env -i". This command here started a shell bash, clearing all other environment variables. After entering " exit» in the called shell bash all variables will be restored.

$ VAR2="TecMint is best Site for Linux Articles" $ echo $VAR2 $ env -i bash $ echo $VAR2

2. Setting and removing user environment variables in Linux.

a) Change the file .bashrc in your home directory to export or set the environment variable you want to add. After that, run the file for the changes to take effect. Then you will see the variable ("CD" in my case) that has taken effect. This variable will be available every time you open a new terminal for this user, but not for remote login sessions.

$ vi .bashrc

.bashrc.

Export CD="This is TecMint Home"

Now run the following command for the new changes to take effect and test the variable.

$ source .bashrc $ echo $CD

To remove this variable, simply delete the line in the file. bashrc and re-enter the shell.

b) To add a variable that will be available for remote login sessions, modify the file .bash_profile.

$ vi .bash_profile

Add the following line to the file .bash_profile.

Export VAR2="This is TecMint Home"

The variable will be available when execute remote using ssh login for that user, but not while opening a new local terminal.

$ source .bash_profile $ echo $ var2

Here VAR2 not initially available, but when you log in remotely using ssh user on localhost, the variable becomes available.

$ ssh $ echo $ var2

To remove this variable, simply remove the line in the file .bash_profile that you added and re-read the file.

NOTE. These variables will be available at every login for the current user, but not for other users.

3. Setting and removing system environment variables in Linux.

a) To add a non-login system variable (i.e. one that is available to all users when any of them opens a new terminal, but not when there is remote access any user to the machine) add this variable to the file /etc/bash.bashrc.

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

Then re-read the file.

$source /etc/bash.bashrc

This variable will now be available to every user when they open a new terminal.

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

Here the variable is available both for the root user and for the normal user. You can check this by logging in as a different user.

b) If you want some environment variable to be available when any of the users on your computer logged in remotely but did not open any new terminal on local computer, you need to edit the file − /etc/profile .

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

After adding the variable, just re-read the file. Then the variable will be available.

$source/etc/profile $echo $var1

To remove this variable, remove the line from the file /etc/profile and reread it.

c) However, if you want to add a variable to any environment where you want to be available system wide, both for remote login sessions and local sessions for all users, just export the variable to /etc/environment.

Export VAR12="I am available everywhere"

After that, just re-read the file and the changes will take effect.

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

Here, we can see that the environment variable is available for the normal user, the root user, and also for the remote login session.

To clear this variable, simply delete the entry in the file /etc/environment and reread the file.

NOTE. Changes take effect when the file is re-read /etc/environment. But, if not, you may need to log out and log back in.

Ask questions about the article in the comments below.

Thanks for taking the time to read the article!

If you have any questions, ask them in the comments.

Subscribe to our blog updates and stay up to date with the news of the world of infocommunications!

To know more and stand out with knowledge among the crowd of IT people, sign up for Cisco courses from the Cisco Academy, Linux courses from the Linux Professional Institute

  • We will ask you about a convenient time for practice and adjust: we understand that there is not enough time to study.
  • If you want an individual schedule, we will discuss and implement it.
  • We will set clear deadlines for self-organization. A personal curator will be in touch to answer questions, advise and motivate you to adhere to the deadlines for passing exams.
  • We will also help you:

    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. System variables Linux environments 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, be it 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

    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 option. 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

    While working with the server, the shell compiles a lot of information that determines its behavior and access to resources. Some of these options are found in shell settings, others are determined by user input.

    One way the shell keeps track of this information is by using the environment. The environment is an area containing system-defining variables that the shell builds each time a session is started.

    This guide explains how to interact with the environment and read or set environment and shell variables interactively and through configuration files. All steps are performed on an Ubuntu 12.04 VPS, but any modern Linux distribution should work the same way.

    How the environment and its variables work

    Each time a shell session is activated, a process is started to collect and compile information that should be available to the shell and its child processes. The shell gets this data from many different files and settings on the system.

    In general, the environment provides a transmission medium that collects and specifies necessary settings shell process, which in turn passes them to its child processes.

    The environment is in the form of a string containing key-value pairs. Multiple values ​​are usually separated by a colon (:) character. Each pair, in general, looks something like this:

    KEY=value1:value2:...

    If the value contains spaces, double quotes must be used:

    KEY="value with spaces"

    In this case, the key means the variables of one of the two existing species: environment or shell variables.

    Environment Variables are variables that have been defined for the current shell and are inherited by all child shells or processes. Environment variables are used to pass information to processes started from a shell.

    Shell variables are variables that are contained exclusively in the shell in which they were set or defined. They are often used to keep track of current data (such as the current working directory).

    Typically, such variables are denoted with capital letters. This helps users distinguish between environment variables in other contexts.

    Output of shell and environment variables

    Each session keeps track of its shell and environment variables. There are several ways to get them out.

    To view a list of all environment variables, use the env or printenv commands. By default, they will output exactly the same result:

    printenv
    SHELL=/bin/bash
    TERM=xterm
    USER=demuser
    LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd= 40;33;01:or=40;31;01:su=37;41:sg=30;43:ca:...
    MAIL=/var/mail/demouser
    PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
    PWD=/home/demouser
    LANG=en_US.UTF-8
    SHLVL=1
    HOME=/home/demouser
    LOGNAME=demuser
    LESSOPEN=| /usr/bin/lesspipe %s
    LESSCLOSE=/usr/bin/lesspipe %s %s
    _=/usr/bin/printenv

    This is a typical example of the output from the printenv and env commands. These commands differ only in a few individual functions. For example, printenv can ask for the values ​​of individual variables:

    printenv SHELL
    /bin/bash

    The env command allows you to change the environment in which programs are run by passing a set of variable definitions to the command, something like this:

    env VAR1="blahblah" command_to_run command_options

    As mentioned above, child processes usually inherit the environment variables of the parent process, which makes it possible to change values ​​or introduce additional variables for child processes.

    As you can see in the output of the printenv command, many environment variables are created by system files and processes without user intervention.

    But how do you view shell variables?

    The set command is used for this. When entered without additional options, set lists all shell variables, environment variables, local variables, and shell functions:

    set
    BASH=/bin/bash
    BASHOPTS=checkwinsize:cmdhist:expand_aliases:extglob:extquote:force_fignore:histappend:interactive_comments:login_shell:progcomp:promptvars:sourcepath
    BASH_ALIASES=()
    BASH_ARGC=()
    BASH_ARGV=()
    BASH_CMDS=()
    . . .

    As a rule, this list is quite long. To display it in a more convenient format, open it with a pager program:

    This list contains a huge amount of additional information that is not needed at the moment (for example, some bash functions).

    To "clean up" the output, you need to run the set command in POSIX mode, which skips shell functions. This needs to be done in a subshell so as not to change the current environment:

    (set -o posix; set)

    This action will list all environment and shell variables.

    You can also compare this result with the result of the env/printenv commands and try to list only shell variables, but such a list will not be ideal, since these commands print information differently:

    comm-23<(set -o posix; set | sort) <(env | sort)

    Most likely, the list will contain several environment variables, because the set command prints the values ​​in quotes, but the printenv and env commands do not.

    However, it's a great way to view the environment and shell variables set in a given session.

    Such variables are used for all sorts of purposes. They provide an alternative way to set persistent session values ​​between processes without having to make changes to the file.

    Basic environment and shell variables

    Some particularly useful environment and shell variables are very commonly used.

    Below is a list of the main environment variables:

    • SHELL: describes the shell that interprets the entered commands. In most cases, bash is set by default, but this value can be changed if necessary.
    • TERM: Specifies the kind of terminal emulated when the shell starts. Different hardware terminals can be emulated depending on operational requirements. Generally, you don't need to worry about this.
    • USER: current user.
    • PWD: current working directory.
    • OLDPWD: previous working directory. The shell keeps it in case you run the cd - command.
    • LS_COLORS: Specifies the color codes that are used to color-code the output of the ls command. Such output helps the user to read the result of the command faster (for example, to quickly distinguish between file types).
    • MAIL: Path to the user's current mailbox.
    • PATH: List of directories accessed by the system when executing commands. When the user runs the command, the system checks these directories in the specified order for the executable.
    • LANG: Current language and localization settings, including character encoding.
    • HOME: home directory of the current user.
    • _ : last executed command.

    After reviewing the list of environment variables, examine the list of shell variables:

    • BASHOPTS: list of options used when executing bash. This can be used to check if the environment is working properly.
    • BASH_VERSION: the running version of bash in human-readable form.
    • BASH_VERSINFO: bash version in machine-readable format.
    • COLUMNS: defines the width of the output in columns.
    • DIRSTACK: the stack of directories available to the pushd and popd commands.
    • HISTFILESIZE: The maximum number of lines contained in the command history file.
    • HISTSIZE: Number of commands to be memorized in the history list.
    • HOSTNAME: current hostname.
    • IFS: Internal separator for input fields on the command line. The default is a space.
    • PS1: defines the primary prompt string - the appearance of the command line when starting a shell session. The PS2 variable sets the secondary prompt string if the command spans multiple lines.
    • SHELLOPTS: shell options that can be set with set.
    • UID: The unique ID of the current user.

    Setting shell and environment variables

    Below are a few examples to demonstrate the difference between shell and environment variables and explain the syntax for setting these variables.

    Creating shell variables

    First you need to set the shell variables of the current session. This is very simple, all you need to do is provide a name and a value. As already mentioned, capital letters are used to write the names of such variables.

    TEST_VAR="Hello World!"

    This example uses quotation marks because the value contains spaces. Moreover, single quotes must be used here, since the exclamation point is a special character in the bash shell that refers to the command history unless it is escaped or enclosed in single quotes.

    So, the resulting shell variable is valid in the current session, but is not passed to its child processes.

    To verify this, use the grep command on the result of the set command:

    set | grep TEST_VAR
    TEST_VAR="Hello World!"

    You can also check that the given variable is not an environment variable by running grep on the result of the printenv command:

    printenv | grep TEST_VAR

    This action will not produce any result.

    This can be used to open the value of any shell or environment variable.

    echo $TEST_VAR
    hello world!

    As you can see, to refer to the value of a variable, you need to use the $ symbol.

    Again, the resulting variable should not be passed to any child process. To test this, inside your current shell, expand a new bash shell:

    bash
    echo $TEST_VAR

    If you expand a child shell and try to open the contents of a variable, nothing will be displayed. This means everything is working properly.

    To return to your original shell, type exit:

    Creating environment variables

    Now try turning the shell variable into an environment variable. This is done by exporting a variable. The command that performs the export has a corresponding name.

    This command turns a shell variable into an environment variable. To check if everything is done correctly, you can review the list of environment variables again:

    printenv | grep TEST_VAR
    TEST_VAR=Hello World!

    Now this variable is displayed in this list. You can also expand the child shell again:

    bash
    echo $TEST_VAR
    hello world!

    Great! The child shell got the parent shell variable. Try exporting one more variable before leaving the child shell.

    export NEW_VAR="Testing export"

    Check if the variable has been exported:

    printenv | grep NEW_VAR
    NEW_VAR=Testing export

    Now return to the original shell:

    Check if the given variable can be opened:

    Result is not returned

    This is because environment variables are only passed to child processes. There is no built-in way to set parent shell environment variables. In most cases, this prevents programs from affecting the operating environment from which they were launched.

    The NEW_VAR variable has been set as a child shell environment variable. This variable is valid for this shell and its child shells and processes. After the user returned to the original shell, this environment was destroyed.

    Moving and Resetting Variables

    The TEST_VAR variable is still an environment variable. To make it a shell variable again, type:

    export -n TEST_VAR

    Now this variable is no longer an environment variable:

    printenv | grep TEST_VAR

    This is again a shell variable:

    set | grep TEST_VAR
    TEST_VAR="Hello World!"

    To completely reset a variable, be it an environment or shell variable, use the unset command:

    Make sure there is no such variable anymore:

    The result was not displayed because the variable was reset.

    Automatic setting of environment variables

    As already mentioned, many programs use environment variables to determine how they should work. Setting the necessary variables every time a new shell is created is rather inconvenient. In addition, many variables are set immediately upon entry. How to set variables automatically?

    This is a bit more complicated than it looks at first because the bash shell reads a lot of configuration files.

    Shell session types

    The bash shell reads different configuration files depending on how the session was started. The first two types of sessions that define a shell are the start session and the child session.

    Starting, or initial shell(login shell) is a shell session that opens after user authorization. If the user logs into a terminal or logs in via SSH, a start shell will be opened.

    If a new session is started from an authorized (start) session (as a new bash shell was started earlier in the examples), this session will be subsidiary (non-login shell). To open this session, you do not need to go through the authorization procedure.

    Also, shell sessions are interactive and non-interactive.

    interactive session shells (interactive shell) is a session attached to a terminal. A non-interactive shell session is a session that is not attached to a terminal.

    So, shell sessions are classified according to the following aspects: start-child, interactive-non-interactive.

    A normal session opened with SSH is usually an interactive start session. A script run through the command line usually runs in a non-interactive child session. A terminal session is various combinations of these two properties.

    By classifying a session as a start session or a child session, the system understands which files to read to initialize the shell session.

    So, first, the startup session gets the configurations from the /etc/profile. It then looks for the startup shell configuration file in the user's home directory to retrieve the user-defined configurations.

    Such a session reads the files ~/.bash_profile, ~/.bash_login and ~/.profile and does not read other files.

    The child session in turn reads /etc/baash.bashrc and then the user's ~/.bash.rc file to deploy the environment.

    Non-interactive shells read the BASH_ENV environment variable and the specified file to create a new environment.

    How to set environment variables

    As you can see, the configurations are scattered across different files.

    This makes the system very flexible, which is useful in certain situations where you need to set different options for the start and child shells. However, these shells generally use the same settings.

    Fortunately, most Linux distributions specify the child shell's configuration file as the source of the startup shell's configurations. This means that you can define environment variables for both sessions in the child shell's configuration files.

    Typically, both shells use user-specified environment variables. This means that you can set these variables in the ~/.bashrc file.

    Open this file:

    Most likely, it already contains some data. Most of the values ​​given here are bash options and have nothing to do with environment variables. Variables in this file are set in the same way as in the command line:

    export VARNAME=value

    After entering all the necessary variables, close the file. The next time a shell session is started, the variables set here will be read and passed to the shell environment. To tell the current session to read the given file, type:

    source ~/.bashrc

    To set system-wide variables, add them to /etc/profile, /etc/bash.bashrc, or /etc/environment.

    Results

    Shell and environment variables are always present in all shell sessions, so knowing how to work with them is especially useful. They can be used to pass parent process configurations to child processes, as well as configure settings outside of files.

    In certain situations, this provides a number of advantages. For example, some deployment mechanisms rely on environment variables to set up authentication information. This is convenient, since such important data will not be stored in any file, which means that they will be reliably protected from strangers.

    There are many other more common situations in which it may be necessary to read variables or change the system environment. The tools and methods described in this tutorial are an excellent foundation for developing skills in working with variables and using them correctly.

    Tags: ,
    mob_info