Environment variables in linux. Linux Environment Variables, Shell Variables

Environment variables in linux. Linux Environment Variables, Shell Variables

17.11.2023

The concept of a parameter in the shell bash similar to the concept of a variable in conventional programming languages. The parameter name (or identifier) ​​can be a word consisting of alphabetic characters, numbers, and underscores (only the first character of the word cannot be a number), a number, or one of the following special characters: * , @ , # , ? , - (hyphen), $ , ! , 0 , _ (underlining).

A parameter is said to be set or set if a value is assigned to it. The value can also be an empty string. To display the value of a parameter, use the symbol $ before his name. Yes, team

$ echo name

will display the word on the screen name, and the team

$echo $name

will return the value of the name variable (if one is set, of course).

5.6.1 Varieties of parameters

Parameters are divided into three classes: positional parameters, special parameters(the names of which are the special characters just listed) and shell variables.

Names (identifiers) positional parameters consist of one or more digits (not a single zero). The positional parameter values ​​are the arguments that were given when the shell started (the first argument is the value of positional parameter 1, etc.). You can change the value of a positional parameter using the built-in command set. The values ​​of these parameters also change while the shell is executing one of the functions (this will be discussed below, in section 5.8).

Special parameters are patterns, replacement (substitution) of which is carried out as follows.

Table 5.2. Special parameters.

Parameter

Substitution rules

Replaced with positional parameters, starting from the first one. If the replacement is made inside double quotes, then this parameter is replaced with a single word made up of all positional parameters separated by the first character of the special IFS variable (discussed below). That is, ``$*"" is equivalent to ``$1c$2c...", where c is the first character in the value of the IFS variable. If IFS is set to empty or has no value set, the parameters are separated by spaces

Replaced with positional parameters, starting from the first one. If the replacement is made inside double quotes, then each parameter is replaced with a separate word. Thus, `` $@"" is equivalent to ""$1"" ""$2"" ... If there are no positional parameters, then no value is assigned (the @ parameter is simply removed)

Replaced with the decimal value of the number of positional parameters

Replaced by the exit status of the last foreground program channel running

(hyphen)

Replaced with the current set of flag values ​​set using the builtin command set or when starting the shell itself

Replaced with the process identifier (P ID) of the shell

Replaced with the process identifier (P ID) of the most recently executed background (asynchronously executed) command

Replaced with the name of the shell or script to run. If bash runs to execute a batch file, $0 is the name of the file. Otherwise this value is equal to the full path to the shell

(underline)

Replaced with the last argument of the previous command executed (if this is a parameter or variable, then its value is substituted)

The special parameters listed in the table above differ in that they can only be referenced; You cannot assign values ​​to them.

Variable from the shell's point of view, it is a parameter denoted by a name. Values ​​are assigned to variables using the following operator:

$name=value

Where name is the name of the variable, and value— the value assigned to it (can be an empty string). The variable name can only consist of numbers and letters and cannot begin with a number. The value can be any text. If a value contains special characters, it must be enclosed in quotes. The assigned value does not contain these quotes, of course. If the variable is set, it can be removed using the shell builtin command unset.

The set of all set shell variables with their assigned values ​​is called the environment or shell environment. You can view it using the command set without parameters (just maybe you should organize a pipeline "set | less"). The output of this command lists all environment variables in alphabetical order. To view the value of one specific variable, you can instead of the command set(in the output of which you can still search and search for the desired variable) you can use the command

$echo $name

(however, in this case you must know the name of the variable you are interested in).

Among the variables you will see in the command output are set, there are some very interesting variables. For example, pay attention to the RANDOM variable. If you run the command several times in a row

$ echo $RANDOM

you will get a new value each time. The fact is that this variable returns a random integer from the interval 0 - 32,768.

5.6.2 Shell prompts

One of the very important variables has a name PS1. This variable specifies the type of invitation that bash Outputs when it is waiting for the next command to be entered by the user. By default, this variable is set to "\s-\v\$ ". Actually in bash There are four invitations that are used in different situations. Variable PS1 specifies the type of prompt that is issued when the shell is waiting for a command to be entered. Secondary prompt specified by variable PS2, appears when the shell is waiting for the user to enter some more data necessary for the continuation of the running command or program. Default variable PS2 has the meaning " >" . You may have already seen this prompt when you ran the command cat to enter data from the keyboard into a file. Another example is the command ftp, after launching which the invitation also takes this form.

Variable prompt PS3, used in command select. Variable prompt PS4, is printed before each command at the time bash monitors the progress of execution. The default value is " + ".

If you so desire, you can change the type of variables PS1 And PS2. In this case, you can use any symbols entered from the keyboard, as well as a certain number of special characters, which, when generating the prompt string, are decoded in accordance with Table. 5.3 (we list only some of them, for example; for a complete list, see the man page for the utility bash) .

Table 5.3. Special characters for generating an invitation

Symbol

Its meaning

Beep (ASCII code 07)

Date in the format "Day, month, day", for example, Wed, Oct, 17.

Hostname up to the first dot

Full hostname

Current time in 24-hour format: HH:MM:SS (hours:minutes:seconds)

Current time in 12 hour format: HH:MM:SS

Current time in 12-hour format am/pm

Name of the user who started the shell

Full name of the current working directory (starting at root)

Current working directory (no path specified)

The # symbol if the shell is running as superuser, and the symbol $ , if the shell is started by a normal user.

\nnn

The character having the octal code nnn

New line (line feed)

Shell name

Current team number

A backslash

Beginning of a sequence of non-printing characters (this character can be used to include a sequence of terminal control characters in the tooltip text)

End of sequence of non-printable characters

The serial number of this command in the history of commands

The current command number (the serial number of the command being executed within the current session) may differ from the number of this command in the command history list, since the latter includes commands that were saved in the command history file.

Once the value of a variable defining a hint has been read by the shell, substitutions can be made to it according to the rules for parameter expansion, substitutions in command names and arithmetic expressions, and word splitting. These rules will be discussed below, in section. 5.7.

For example, after executing the command (since there is a space in the string, quotes are required)

# PS1="[\u@\h \W]\$"

the standard prompt will display a square bracket, username, symbol @ , computer name, space, current directory name (without path), closing square bracket and symbol $ (if a simple user is running in the shell) or # (if the shell is running as root).

5.6.3 Variable PATH

Another very important variable has a name PATH. It specifies a list of paths to directories in which bash searches for files (in particular, files with commands) in cases where the full path to the file is not specified on the command line. Individual directories in this list are separated by colons. Default variable PATH includes directories /usr/local/bin, /bin, /usr/bin, /usr/X11R6/bin, i.e. it looks like:

/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:

In order to add a directory to this list, you need to run the following command:

# PATH=$PATH:new_path.

When performing a search, the shell searches the directories in the order they are listed in the PATH variable.

Note that you can include the current directory in this list by adding a period to the PATH variable. However, this is not recommended for security reasons: an attacker could put a command in a public directory whose name matches one of the commands frequently executed by the superuser, but performs completely different actions (especially if the current directory is at the beginning of the list of search paths).

5.6.4 Variable IFS

This variable specifies the Internal Field Separator that is used in the word splitting operation of command line conversions performed by the shell before running the command line for execution. The default value of this variable is "<Пробел><Символ_ новой_ строки>".

5.6.5 Current and home directories

The name of the current directory is stored in an environment variable (named PWD), and the value of this variable changes each time the program is started CD(and also when changing the current directory in any other way, for example, through Midnight Commander).

Similarly, the full name (and path) of the home directory of the user who launched the process is stored in the HOME variable.

5.6.6 Team export

When the shell runs a program or command, it passes some environment variables to them. In order for an environment variable to be passed to a process launched from the shell, it must be set using a special command export, i.e. instead

$name=value

need to write it down

$export name=value

In this case, all programs launched from the shell (including secondary instances of the shell itself) will have access to the variables defined in this way, i.e., they can call their values ​​by name.

V. Kostromin (kos at rus-linux dot net) - 5.6. Parameters and variables. Shell environment

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

For example the command P.W.D. 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 setting up 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 deleted using a special set of commands.

2. User environment variable

These are variables that are defined for a specific user and are loaded whenever the user logs in using a local terminal session or if that user logs in using a remote login session. These variables are typically 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, to all users present on that system. These variables are present in system-wide configuration files, present in the following directories and files: /etc/environment,/etc/profile, /etc/profile.d/, /etc/bash.bashrc. These variables are loaded every time the system is turned on and users log in, either locally or remotely.

Understanding General 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 every time the user logs in remotely, that is, using the command ssh. If this file does not exist, the system searches for files .bash_login or .profile.

/etc/environment

This file is the system file for creating, editing or deleting any environment variables. Environment variables created in this file are available throughout the system, to each 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 removed 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 his local system.

Note. Environment variables created using system-wide or user configuration files can be removed, but can only be removed from those files. Just after each change to these files, either log out or log in again or simply type the following command on your 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

By default the command " 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 execute 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 that you want to use only with this command.

$ env -i bash

We launch a bash shell, which will temporarily clear all environment variables. 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 remove or clear.

3. Set the variable name using 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=(after equals there is nothing - 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 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. Then we use unset and at the end we delete this variable.

$ VAR1="TecMint is the 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 empty.

$ 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 the shell bash, clearing all other environment variables. After entering " exit" in the called shell bash all variables will be restored.

$ VAR2="TecMint is the 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 to be added. 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 that user, but not for remote login sessions.

$vi.bashrc

.bashrc.

Export CD="This is TecMint Home"

Now run the following command to make the new changes 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 you execute remote using ssh login for that user, but not while opening a new local terminal.

$source.bash_profile $echo $VAR2

Here VAR2 initially not available, but when performing a remote login using ssh user on localhost the variable becomes available.

$ssh$echo$VAR2

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

NOTE: These variables will be available on 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 (that is, one that is available to all users when any of them opens a new terminal, but not when there is remote access to any user to the machine), add this variable to the file /etc/bash.bashrc.

Export VAR="This is system-wide variable"

After that, re-read the file.

$ source /etc/bash.bashrc

Now this variable will be available to each user when he opens a new terminal.

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

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

b) If you want any environment variable to be available when any of the users on your computer logged in remotely but did not open any new terminal on the 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, simply re-read the file. Then the variable will be available.

$source/etc/profile $echo $VAR1

To remove this variable, delete the line from the file /etc/profile and re-read it.

c) However, if you want to add a variable to any environment where you want to be available system wide, for both remote login sessions and local sessions for all users, simply 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 reread /etc/environment. But, if not, you may need to log out and log in again.

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 news from the world of infocommunications!

To know more and stand out among the IT crowd with knowledge, 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 little 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 supervisor will be in touch to answer questions, advise and motivate you to adhere to exam deadlines.
  • We will also help you:

    Original: Linux Fundamentals
    Author: Paul Cobbaut
    Published date: October 16, 2014
    Translation: A. Panin
    Translation date: December 13, 2014

    Chapter 12. Shell Variables

    In this chapter, we will learn how to work with environment variables using the command shell. These variables are typically required for applications to function.

    Dollar symbol ($)

    Another important symbol interpreted by the shell is the dollar symbol $. The command shell will look for an environment variable with a name corresponding to the line after the dollar sign, and replace that symbol and the variable name with the value of that variable (or with nothing if the variable does not exist).

    Below are some examples of using the $HOSTNAME, $USER, $UID, $SHELL and $HOME variables. $ echo This is the shell $SHELL This is the /bin/bash shell $ echo This is the $SHELL shell used on the computer $HOSTNAME This is the /bin/bash shell used on the computer RHELv4u3.localdomain $ echo The user ID $USER is equal to $UID The user ID paul is equal to $500 echo My home directory is $HOME My home directory is /home/paul

    Case sensitivity

    This example shows that shell variable names are case sensitive! $ echo Hello $USER Hello paul $ echo Hello $user Hello

    Creating Variables

    This example creates the $MyVar variable and then sets its value. The example then uses the echo command to check the value of the created variable. $ MyVar=555 $ echo $MyVar 555 $

    Quotes

    Note that double quotes also allow expansion of variables on the command line, while single quotes prevent such expansion. $ MyVar=555 $ echo $MyVar 555 $ echo "$MyVar" 555 $ echo "$MyVar" $MyVar

    The bash shell will replace variables with their values ​​in double-quoted lines, but will not do so in single-quoted lines. paul@laika:~$ city=Burtonville paul@laika:~$ echo "We are now in $city." Now we are in the city of Burtonville. paul@laika:~$ echo "We are now in $city." We are now in $city.

    set command

    You can use the set command to list environment variables. On Ubuntu and Debian systems, the set command will also list shell functions after the list of shell variables. Therefore, to familiarize yourself with all elements of the list of environment variables when working with these systems, it is recommended to use the set | more.

    unset command

    You should use the unset command to remove a variable from your shell environment. $ MyVar=8472 $ echo $MyVar 8472 $ unset MyVar $ echo $MyVar $

    Environment variable $PS1

    The $PS1 environment variable sets the greeting format for your shell. When entering a format string, you can use a backslash to escape special characters such as \u for the username or \w for the working directory. The bash shell man page provides a complete list of special characters.

    In the example below, we change the value of the $PS1 environment variable several times. paul@deb503:~$ PS1=invitation invitation invitationPS1="invitation " invitation invitation PS1="> " > > PS1="\u@\h$ " paul@deb503$ paul@deb503$ PS1="\u@\h :\W$" paul@deb503:~$

    To avoid fatal errors, you can use green for shell prompts displayed to standard users and red for shell prompts displayed to root. Add the following lines to your .bashrc file to use green in the prompts displayed to regular users. # colored shell prompt created by paul RED="\[\033" WHITE="\[\033" GREEN="\[\033" BLUE="\[\033" export PS1="$(debian_chroot:+( $debian_chroot))$GREEN\u$WHITE@$BLUE\h$WHITE\w\$ "

    $PATH environment variable

    The $PATH environment variable sets the file system directories in which the shell looks for binaries needed to execute commands (unless the command is a builtin or is represented by a command alias). This variable contains a list of directory paths separated by colon characters. [$ echo $PATH /usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:

    The command shell will not search the current directory for executable binaries. (The search function for executable files in the current directory was the simplest mechanism for unauthorized access to data stored on computers running PC-DOS). If you want the shell to search for executable files in the current directory, you should add the symbol. to the end of the line that is the value of your shell's $PATH variable. $PATH=$PATH:. $ echo $PATH /usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:. $

    The value of your shell's $PATH variable may be different if you use the su command instead of the su - command, since the latter command allows additional use of the target user's environment variable values. For example, the list of directories for the root user, represented by the value of the $PATH variable, usually includes the /sbin directories. $ su Password: # echo $PATH /usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin # exit $ su - Password: # echo $PATH /usr/local/sbin:/usr/ local/bin:/sbin:/bin:/usr/sbin:/usr/bin: #

    env command

    The env command, when used without parameters, will display a list of exported environment variables. The difference between this command and the set command with parameters is that the set command lists all environment variables, including those variables that are not exported to child shells.

    Additionally, the env command can also be used to launch a "pure" shell (a shell without inheriting any environment). The env -i command allows you to clear the environment of a child shell.

    One thing to note when considering this example is that the bash shell will set the $SHELL environment variable to the value when it starts. $ bash -c "echo $SHELL $HOME $USER" /bin/bash /home/paul paul $ env -i bash -c "echo $SHELL $HOME $USER" /bin/bash $

    You can use the env command to set the value of the $LANG variable or any other environment variable of a single bash shell instance within a single command. The example below uses this feature to demonstrate the impact of the value of the $LANG variable on the operation of the file pattern search mechanism (for more information on this mechanism, see the chapter on file pattern search). $ env LANG=C bash -c "ls File" Filea Fileb $ env LANG=en_US.UTF-8 bash -c "ls File" Filea FileA Fileb FileB $

    export command

    You can export shell variables to other shells using the export command. In the example below, this command exports an environment variable to child shells. $ var3=three $ var4=four $ export var4 $ echo $var3 $var4 three four $ bash $ echo $var3 $var4 four

    However, using this command, the variable is not exported to the parent command shell (the previous example is continued below). $ export var5=five $ echo $var3 $var4 $var5 four five $ exit exit $ echo $var3 $var4 $var5 three four $

    Variable delimitation

    Until now, we have seen that the bash shell interprets a variable starting with a dollar sign and continuing until the first non-alphanumeric character that is not an underscore appears. In some situations this behavior can be problematic. To solve this problem, curly braces can be used in the manner shown in the example below. $ prefix=Super $ echo Hello $prefixman and $prefixgirl Hello and $ echo Hello $(prefix)man and $(prefix)girl Hello Superman and Supergirl $

    Unbound Variables

    The example below attempts to display the value of the $MyVar variable, but is unsuccessful due to the fact that the variable does not exist. By default, the shell will not print anything if the variable is not bound (it does not exist). $ echo $MyVar$

    However, there is a nounset shell option that you can use to generate an error if the variable you are using does not exist. paul@laika:~$ set -u paul@laika:~$ echo $Myvar bash: Myvar: unbound variable paul@laika:~$ set +u paul@laika:~$ echo $Myvar paul@laika:~$

    In the bash shell, the set -u command is identical to the set -o nounset command and, similarly, the set +u command is identical to the set +o nounset command.

    Practice: Shell Variables

    2. Create a variable answer whose value is 42.

    3. Copy the value of the $LANG variable to the value of the $MyLANG variable.

    4. List the shell variables currently in use.

    5. List all exported shell variables.

    6. Is information about your variable present in the output of the env and set commands?

    7. Destroy your answer variable.

    8. Create two variables and export one of them.

    9. Print the value of the exported variable in the child interactive command shell.

    10. Create a variable and assign it the value "Dumb", then create another variable with the value "do" in the same way. Use the echo command and the two created variables to print the word "Dumbledore".

    11. Find a list of backslash-escaped control characters in the bash shell man page. Add a control character to the PS1 variable to display the time in the shell greeting.

    Correct Procedure for Practice: Shell Variables

    1. Use the echo command to print the string "Hello" followed by your name. (Use a bash shell variable!)

    Objects that are named and contain data used by at least one, usually several, applications are called environment variables. In simple terms, an environment variable is nothing more than a variable that has a name and a value.

    Environment variable values ​​can be the default editor to be used, such as the location of all files that can be executed on the system, or local settings for the system. It's a little complicated for beginners, but an environment variable is a great way to share configuration settings across multiple applications and processes.

    The Coreutils package contains the env and printenv programs. To list all environment variables that currently have a value, simply type:

    $printenv

    There are two types of environment variables in the bash shell:

    • Global Variables
    • Local Variables

    Global Environment Variables

    From the shell session, global environment variables and any child processes that the shell generates are displayed.

    On the other hand, local variables can only be accessed by the shell when they are created. This makes global environment variables useful in applications that require information from a parent process and spawn child processes.

    By default, the Linux system sets certain global environment variables when starting a bash session. System environment variables use all capital letters each time to distinguish them from normal user environment variables.

    Local Environment Variables

    Because their name indicates that local environment variables can only be visible in the local process in which they are defined. Don't get confused though about local environment variables, they are equally important as global environment variables. In fact, the Linux system will also define standard local environment variables for you by default. This gets tricky when you try to see a list of local environment variables. Unfortunately, there is no command for us that will display only local environment variables. There is a command that displays all the environment variables set for a particular process. Note that this also includes global environment variables.

    Setting Environment Variables

    You can create your own environment variables directly from the bash shell. In the next section, we'll show you how to create your own environment variables and reference them from your interactive shell or shell program.

    Setting Local Environment Variables

    Once a bash shell has started (or a shell script has appeared), you are allowed to create local variables that are visible within your shell process. You can assign an environment variable to a string or numeric variable using the equals sign, which assigns the value of the variable:

    $ andreyex_test=testing $ echo $andreyex_test testing $

    Congratulations, you have just created your first variable. Just remember that any time you need to reference the value of the andreyex_test environment variable, just reference it by the name $andreyex_test.

    If you need to assign a string of values ​​containing spaces, you will need to use a single quote to indicate the start and end of the string:

    $ andreyex_test=testing a long string -bash: a: command not found $ andreyex_test="testing a long string" $ echo $andreyex_test testing a long string

    If left without the single quotes, the bash shell assumes that the next character is another command to process.

    Note that for the local environment variable we defined we used all lowercase letters, the system environment variables we have seen so far have used all uppercase letters.

    In the bash shell, this is the standard convention. If you are setting up new environment variables, this is not required, but lowercase is recommended. This helps differentiate your personal environment variables from the results of system environment variables.

    NOTE: It is very important that there are no spaces between the environment variable name, the equals sign, and the value. If you put any spaces in the assignment, the bash shell interprets the value as a separate command:

    $ andreyex_test2 = test -bash: andreyex_test2: command not found $

    A local environment variable set in your shell process will be available for use anywhere in your shell process. But if you create another shell, it is not available in the child shell:

    $ bash $ echo $andreyex_test $ exit exit $ echo $andreyex_test testing a long string $

    In this case, we started a child shell. As you can notice, the andreyex_test environment variable is not available in the child shell (it contains an empty value). After we left the child shell and returned to the original shell, the local environment variable was still available.

    Likewise, if you set a local environment variable in a child process after you leave the child process, the local environment variable is no longer accessible:

    $ bash $ andreyex_test=testing $ echo $andreyex_test testing $ exit exit $ echo $andreyex_test $

    The andreyex_test environment variable set in the child shell does not exist when we return to the parent shell.

    Setting Global Environment Variables

    Global environment variables are visible from all processes of the child process created by the process that sets the global environment variable. The method used to create a global environment variable is to create a local environment variable and then export it to the global environment.

    This is done using the export command:

    $ echo $andreyex_test testing a long string $ export andreyex_test $ bash $ echo $andreyex_test testing a long string $

    After we use the export command in the local environment variable andreyex_test, we started a new shell process and looked at the value of the andreyex_test environment variable. This time, the export command made the global environment variable global, so it retained its value.

    Note that when you run a command export in a local environment variable, you do not use a dollar sign to refer to the variable name.

    Removing Environment Variables

    Obviously, if you can create a new environment variable, it would make sense that you could also delete the existing environment variable. This can be done using the unset command:

    $ echo $andreyex_test testing $ unset andreyex_test $ echo $andreyex_test $

    If you reference an environment variable in the unset command, be aware not to use the dollar sign.

    When working with global environment variables, things get a little more complicated. If you are in a child process and you disable the global environment variable, it only applies to the child process. The global environment variable remains available in the parent process:

    $ andreyex_test=testing $ export andreyex_test $ bash $ echo $andreyex_test testing $ unset andreyex_test $ echo $andreyex_test $ exit exit $ echo $andreyex_test testing $

    In this example, we set a local environment variable called andreyex_test, then export it to make it a global environment variable. We then started the child shell process and were checked to ensure that the global environment variable andreyex_test was still available. Then, while still in the child shell, we used the unset command to remove the andreyex_test global environment variable and then exited the child shell. Now back to the original parent shell, we checked the value of the andreyex_test environment variable and it is still valid.

    Default Shell Environment Variables

    There are specific environment variables that the bash shell uses to determine the system environment. You can always count these variables to be used on your Linux system. Because the bash shell is a derivative of the original Unix Bourne shell, it also includes the environment variables originally defined in that shell.

    The following examples show that the environment variables provided by the bash shell are compatible with the original Unix Bourne shell.

    By far the most valuable environment variable on this list is the PATH environment variable.

    When you enter a command in a shell command shell (command line interface), the shell must search the system to find the program. The directories it searches for commands are determined by the PATH environment variable. On a Linux system, the PATH environment variable should look something like this:

    $ echo $PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin $

    This case shows that there are eight directories in which the shell looks for commands. Each directory is separated by a colon, and there is no end to the list of directories at the end of the PATH variable. You can always add additional directories to PATH by adding a new directory and adding another colon. PATH also shows the query where it looks for orders.

    In addition to the standard Bourne environment variables, the bash shell also provides several variables, as shown:

    Bash Shell Bourne Variables:

    CDPATH: A colon-separated list of directories used as the search path for the cd command.
    HOME: The current user's home directory.
    IFS: A list of characters that separate fields used by the shell to separate text strings.
    MAIL: The file name for the current user's mailbox. The bash shell checks this file for new mail.
    MAILPATH: A list of multiple filenames for the current user's mailbox. The bash shell checks each file in this list for new mail.
    OPTARG: The value of the last parameter argument processed by the getopts command.
    OPTIND: The index value of the last parameter argument processed by the getopts command.
    PATH: A colon-separated list of directories where the shell looks for commands.
    PS1: Main command line prompt string.
    PS2: Secondary shell command line interface prompt string.

    Shell bash environment variables:

    BASH: The fully qualified path name to execute the current instance of the bash shell.
    BASH_ENV: When installed, each bash script attempts to run the startup file defined by this variable before running.
    BASH_VERSION: The version number of the current bash shell instance.
    BASH_VERSINFO: An array of variables containing the individual major and minor version numbers of the current instance of the bash shell.
    COLUMNS: Contains the terminal width used for the current bash shell instance.
    COMP_CWORD: An index into the COMP_WORDS variable that contains the current cursor position.
    COMP_LINE: Current command line.
    COMP_POINT: index of the current cursor position relative to the start of the current command.
    COMP_WORDS: A variable array containing the individual words on the current command line.
    COMPREPLY: A variable array containing possible exit codes generated by the shell function.
    DIRSTACK: An array of variables containing the current contents of the directory stack.
    EUID: The effective user ID of the current user.
    FCEDIT: The default editor used by the fc command.
    FIGNORE: A colon-separated list of suffixes to ignore when performing filename completion.
    FUNCNAME: The name of the currently executing shell function.
    GLOBIGNORE: A colon-separated list of patterns specifying a set of filenames to ignore when expanding the filename.
    GROUPS: A variable array containing a list of groups of which the current user is a member.
    histchars: up to three characters that control history expansion.
    HISTCMD: history number of the current command.
    HISTCONTROL: Controls which commands are entered in the shell history list.
    HISTFILE: The file name to save the shell history list (default is history.bash).
    HISTFILESIZE: The maximum number of lines to store in the history file.
    HISTIGNORE: A colon-separated list of patterns used to determine which commands are ignored for the history file.
    HISTSIZE: The maximum number of commands stored in the history file.
    HOSTFILE: Contains the name of the file that should be read when the shell needs to fill in the hostname.
    HOSTNAME: The name of the current host.
    HOSTTYPE: String describing the bash-shell machine running.
    IGNOREEOF: The number of consecutive EOF characters the shell must receive before exiting. If this value does not exist, it defaults to one.
    INPUTRC: Readline initialization file name (default is .inputrc).
    LANG: The locale category for the shell.
    LC_ALL: Overrides the LANG variable to specify the locale category.
    LC_COLLATE: Sets the collation order used when sorting string values.
    LC_CTYPE: Determines the interpretation of characters used in file name expansion and pattern matching.
    LC_MESSAGES: Defines the locale setting used when interpreting double-quoted strings preceded by a dollar sign.
    LC_NUMERIC: Specifies the local setting used to format numbers.
    LINENO: Line number in the script being executed.
    LINES: Determines the number of lines available on the terminal.
    MACHTYPE: A string defining the system type in the format cpu-company-system.
    MAILCHECK: How often the shell should check (default 60 seconds) for new mail.
    OLDPWD: Previous working directory used in the shell.
    OPTERR: If set to 1, the bash shell displays errors generated by the getopts command.
    OSTYPE: A string identifying the operating system the shell is running on.
    PIPESTATUS: A variable array containing a list of the foreground process's process exit status values.
    POSIXLY_CORRECT: If set, bash runs in POSIX mode.
    PPID: Process ID (PID) of the parent bash shell process.
    PROMPT_COMMAND: If set, the command to execute before the initial prompt is displayed.
    PS3: prompt to use select command.
    PS4: Prompt displayed before the command line is echoed if the bash -x option is used.
    PWD: current working directory.
    RANDOM: Returns a random number between 0 and 32767. Assigning a value to this variable will generate a random number generator.
    REPLY: Default variable for read command.
    SECONDS: The number of seconds since the shell started. Assigning a value resets the timer to the value.
    SHELLOPTS: A colon-separated list of allowed bash shell options.
    SHLVL: Specifies the shell level, incremented by one each time a new bash shell is started.
    TIMEFORMAT: A format that determines how the shell displays time values.
    TMOUT: A value for how long (in seconds) select and read commands should wait for input. The default value of zero means wait indefinitely.
    UID: The real user ID of the current user.

    You may notice that after using the set command, not all default environment variables are displayed. An explanation for this could be that although these are default environment variables, not all of them need to contain a value.

    Conclusion

    In this guide, we explored the world of Linux environment variables. Global environment variables are often accessed by any child process spawned by the process in which they are defined. Local environment variables will only be accessible from the process in which they are defined.

    The Linux system uses each global and local environment variables to store information about the system environment. You will be able to access this information from the shell command line interface as well as internal shell scripts. The bash shell uses the system environment variables defined in the original UNO Bourne shell, as well as many new environment variables. The PATH environment variable defines the search pattern that the bash shell accepts when searching for an executable command. You will be able to change the PATH environment variable to add your own directories, or perhaps the current directory symbol, to make your programs easier to work with. You can also create your own global and local environment variables for your own use. Once an environment variable is created, it is available to the entire shell session.

    There are many startup files that start the bash shell once it has started. These startup files may contain environment variable definitions to set standard environment variables for each bash session. After logging into a Linux system, the bash shell accesses the /etc/profile startup file, as well as three local startup files for each user, $HOME/.bash, $HOME/.bash login, and $HOME/.profile.

    Users will customize these files to include environment variables and startup scripts for their own use. The bash shell additionally provides environment variable arrays. These environment variables can contain multiple values ​​in a single variable. You will be able to access the values ​​individually by specifying an index value or as a whole by specifying the fully qualified environment variable array name. Finally, in this guide we must mention the use of command aliases. Although not environment variables, command aliases behave almost like environment variables. They allow you to define an alias for a command along with its parameters. Instead of typing a very long command and parameters, you will be able to simply give it a simple alias and use the alias at any time in your shell session.

    2.2. Environment Variables

    The operating system supports a special type 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, precede the variable name with a $ sign:

    $ echo $USER guest

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

    To set the value of a variable, use the assignment operator (in the case of Bourne-like shells):

    $TEST=test

    or the built-in set operator (in the case of C-like ones):

    $ 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 for a given process or global for a session. You can set local values ​​for variables by preceding them by calling the commands:

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

    You can evaluate the contents of a set of variables for a session by calling the interpreter's built-in command env in the case of Bourne-like interpreters (sh, ksh, bash, zsh, pdksh...), and printenv in the case of 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 compiled into command files called scripts, where the first line in a special type of comment specifies 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 print to standard output the text message "TEST variable: " and the value of the TEST variable, if specified. You can run it from the command line by passing it as a parameter to the command interpreter:

    $sh test TEST variable:

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

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

    You can set local values ​​of variables for executing a given program by preceding them by calling the commands:

    $ TEST=test2 sh test TEST variable: test2

    Removing environment variables is done using the unset statement.

    © 2023 hecc.ru - Computer technology news