[Linux] An article to get environment variables

Environment variable

1. What are environment variables

  • Definition: Environment variables (environment variables) generally refer to some parameters used in the operating system to specify the operating environment of the operating system

Simply put, it is the variable of the system operating environment configuration

2. The role of environment variables

  • Setting parameters: Environment variables are equivalent to setting some parameters for the system or user applications. The specific function depends on what the user or the system originally defined it for . For example, when a program is required to run without telling it where the program is located, the system will Look for the program in the current directory, and look for the environment variable PATH

3. Configure environment variables on the command line

Five important commands: env echo export set unset

View environment variables—env

Display all the environment variables defined in the current system, each of which is displayed in the form of **key-value pair (NAME=VALUE)**

[gongruiyang@localhost ~]$ env

image.png

The most important of these variables is the PATH environment variable. This environment variable stores the default search path for program execution , which will be explained in detail later.

Print the content of a variable—echo

Echo is a command used to display and print

echo string -> print the string as it is

echo $string—> The string behind $ is a variable name, and the variable value is printed

[gongruiyang@localhost ~]$ echo PATH
PATH
[gongruiyang@localhost ~]$ MyValue=2020     <---自定义变量
[gongruiyang@localhost ~]$ echo $MyValue    <---查看自定义变量
2020
[gongruiyang@localhost ~]$ echo $PATH           <---查看环境变量
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/gongruiyang/.local/bin:/home/gongruiyang/bin:/home/gongruiyang/ClassLinunx

View variable content—set

View the contents of all variables, you can view both environment variables and custom variables

[gongruiyang@localhost ~]$ MyValue=2020     <---自定义变量
[gongruiyang@localhost ~]$ echo $MyValue    <---查看变量
2020
[gongruiyang@localhost ~]$ env | grep MyValue       <---在环境变量中寻找MyValue变量,没有找到
[gongruiyang@localhost ~]$ set | grep MyValue       <---在所有变量中寻找MyValue变量,找到了并打印
MyValue=2020

Declare and define conversion variables—export

Convert custom variables into environment variables

[gongruiyang@localhost ~]$ export MyValue               <---将自定义变量MyValue转换为环境变量
[gongruiyang@localhost ~]$ env | grep MyValue       <---在环境变量中寻找MyValue变量,找到了并打印
MyValue=2020
[gongruiyang@localhost ~]$ export MV=1999               <---声明并定义并添加环境变量MV
[gongruiyang@localhost ~]$ env | grep MV
MV=1999

Delete variable—unset

The unset command can delete custom variables and environment variables

[gongruiyang@localhost ~]$ BBBB=100
[gongruiyang@localhost ~]$ set | grep BBBB
BBBB=100
[gongruiyang@localhost ~]$ env | grep BBBB
[gongruiyang@localhost ~]$ export BBBB
[gongruiyang@localhost ~]$ set | grep BBBB
BBBB=100
[gongruiyang@localhost ~]$ env | grep BBBB
BBBB=100
[gongruiyang@localhost ~]$ unset BBBB               <---将变量BBBB删除
[gongruiyang@localhost ~]$ set | grep BBBB
[gongruiyang@localhost ~]$ env | grep BBBB

4. Configure environment variables in the code

Get environment variables

Method 1: getenv function

char *getenv(const char *name);

name: name of environment variable

Return value: the first address of the environment variable content

Use the command line to view the TESTVALUE environment variable:

image.png

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
 
int main()
{
    
    
  //通过环境变量名称获取环境变量值                                           
  char *temp = getenv("TESTVALUE");
  if(temp == NULL)
    printf("No env var : TESTVALUE\n");
   else
    printf("TESTVALUE:[%s]\n",temp);
 
   return 0;
 }

The results are as follows:

image.png

Method 2: The third parameter of main

Explanation: As long as the main function is run, the environment variables will be passed in. We don't usually use environment variables, so we didn't receive it.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int agrc,char *argv[],char *env[])
{
    
    
  int i;
  for(i=0;env[i]!=NULL;i++)
    printf("env[%d]:[%s]\n",i,env[i]);
                                           
  return 0;
}

Output: the environment variable to the key to the way output

[gongruiyang@localhost ClassLinunx]$ vim env.c
[gongruiyang@localhost ClassLinunx]$ make
gcc env.c -o env
[gongruiyang@localhost ClassLinunx]$ ./env 
env[0]:[XDG_SESSION_ID=3]
env[1]:[HOSTNAME=localhost.localdomain]
env[2]:[SELINUX_ROLE_REQUESTED=]
env[3]:[TERM=xterm]
env[4]:[SHELL=/bin/bash]
env[5]:[HISTSIZE=1000]
env[6]:[SSH_CLIENT=192.168.233.1 58862 22]
env[7]:[SELINUX_USE_CURRENT_RANGE=]
env[8]:[OLDPWD=/home/gongruiyang]
env[9]:[SSH_TTY=/dev/pts/0]
env[10]:[USER=gongruiyang]
env[11]:[LD_LIBRARY_PATH=:/home/gongruiyang/.VimForCpp/vim/bundle/YCM.so/el7.x86_64]
..................................................

Method 3: Declare the environ variable in the library

Attention! The variable environ exists in the library, you only need to use the extern declaration to introduce the variable!

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int agrc,char *argv[])
{
    
    
  extern char** environ;
  
  for(int i = 0; env[i]!=NULL;i++)
    printf("environ[%d]:[%s]\n",i,environ[i]);
                                              
  return 0;                      
}                                

Output result:

[gongruiyang@localhost ClassLinunx]$ ./env 
environ[0]:[XDG_SESSION_ID=3]
environ[1]:[HOSTNAME=localhost.localdomain]
environ[2]:[SELINUX_ROLE_REQUESTED=]
environ[3]:[TERM=xterm]
environ[4]:[SHELL=/bin/bash]
environ[5]:[HISTSIZE=1000]
environ[6]:[SSH_CLIENT=192.168.233.1 58862 22]
environ[7]:[SELINUX_USE_CURRENT_RANGE=]
environ[8]:[OLDPWD=/home/gongruiyang]
environ[9]:[SSH_TTY=/dev/pts/0]
environ[10]:[USER=gongruiyang]
environ[11]:[LD_LIBRARY_PATH=:/home/gongruiyang/.VimForCpp/vim/bundle/YCM.so/el7.x86_64]
.........................................

Set environment variables

Method one: setenv function

Function: ①Add a non-existent environment variable ②Modify the value of an existing environment variable

int setenv( const char *name , const char *value , int overwrite )

  • parameter list:
  1. name: the name of the environment variable
  2. value: the value of the environment variable
  3. overwrite: 0 means that the original value will not be overwritten if the environment variable already exists; non-zero means that the original value will be overwritten if the environment variable already exists
  • Return value: 0 means success; -1 means error
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int agrc,char *argv[])
{
    
    

  //获取当前系统中环境变量TESTVALUE的值
  printf("Befor:[%s]\n",getenv("TESTVALUE"));

  //设置TESTVALUE的值为2020
  int ret_Modify_setenv = setenv("TESTVALUE","2020",1);
  if(!ret_Modify_setenv)
    printf("Modify success!After:[%s]\n",getenv("TESTVALUE"));
  else
    printf("Modify error!\n");

  //添加一个新的环境变量
  int ret_Add_setenv = setenv("NEWADDVALUE","2020",1);
  if(!ret_Add_setenv)
    printf("Add success!NEWADDVALUE:[%s]\n",getenv("NEWADDVALUE"));
  else
    printf("Add error!\n");                                    

  return 0;
}

[gongruiyang@localhost ClassLinunx]$ vim env.c
[gongruiyang@localhost ClassLinunx]$ make
gcc  env.c -o env
[gongruiyang@localhost ClassLinunx]$ ./env 
Befor:[1000]
Modify success!After:[2020]
Add success!NEWADDVALUE:[2020]

Method 2: putenv function

Role: add or modify environment variables

int putenv( char *string );

  • Parameter list: string -> consists of name=value
  • Return value: 0 means success; non-zero means
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
    
    

  char* string = "MyV=1999";                          

  int ret_putenv = putenv(string);

  //判断是否成功
  if(!ret_putenv)
    printf("put success!string:[%s]\n",getenv("MyV"));
  else
    printf("put error!\n");

  return 0;
}

Program running results:

[gongruiyang@localhost ClassLinunx]$ ./env 
put success!string:[1999]

Delete environment variables

unsetenv function

effect:

int unsetenv( const char *name );

  • Parameter list: name -> environment variable name
  • Return value: 0 means deletion is successful; -1 means deletion failed
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int agrc,char *argv[])
{
    
    
                                                        
  const char* name = "NEWADDVALUE";

  //获取NEWADDVALUE环境变量的值
  printf("%s=%s\n",name,getenv(name));

  //删除NEWADDVALUE环境变量
  int ret_unsetenv = unsetenv(name);
  //判断是否删除成功
  if(ret_unsetenv == 0)
    printf("delete success!%s=%s\n",name,getenv(name));
  else
    printf("delete error!\n");

  return 0;
}

Output result:

[gongruiyang@localhost ClassLinunx]$ ./env 
NEWADDVALUE=2020
delete success!NEWADDVALUE=(null)

5. Storage location of environment variables in memory

image.png

6. Variables about the path of the executable file: $PATH

  • Reference

Think about it: Why can we execute the ls command in any directory in the Linux command line mode?

The full file name of the ls command is: /bin/ls <—this is an absolute path

The reason why we execute ls in any directory in the Linux command line mode will display file information, but will not say that the /bin/ls command cannot be found. This is due to the help of the environment variable PATH

  • principle

Take the ls command as an example. When we enter ls and press Enter, the system knows that you want to execute an executable file named ls. At this time, the system will look for a file named ls in the directory defined in the PATH. Execution file, if there are multiple executable files named ls in the directory defined in PATH, the first file named ls found will be executed first

  • Check which file paths have been defined in PATH

Use the command: echo $PATH

image.png

The above picture prints out which directories are defined in the environment variables under the identity of gongruiyang , and each directory is separated by a colon (:)

So it can be seen that the file directories defined in the environment variables under the identity of gongruiyang are:

/usr/local/bin

/usr/bin

/usr/local/sbin

/usr/sbin

/home/gongruiyang/.local/bin

/home/gongruiyang/bin

Let's take a look at the environment variables under the root identity

image.png

The environment variables in the root identity and gongruiyang identity in my Linux system are the same (yours may be different, this is normal, the contents of the environment variables can be increased, decreased, and modified, which will be described later~)

<: Here you can more clearly know why we can execute ls in any directory in the Linux command line mode, because the user/bin directory is defined in the environment variables under the root identity or under the gongruiyang identity , So the system will search for the ls command in this directory, and execute it when it finds it

Summary: Environment variables are composed of a bunch of directories, separated by colons, and each directory has a priority


  • expand

Think about it: How to make the executable program file we write can be run no matter which directory it is in?

We wrote a program that outputs one sentence

#include <stdio.h>  
  
int main()  
{
    
      
  printf("This is AKA giao, peace & love.\n"); 
                                    
  return 0;                         
}                                   

Use the command to compile it into an executable file Mytest

gcc test.c -o test

We can execute the test executable file in the /home/gongruiyang/ClassLinunx directory

[gongruiyang@localhost ClassLinunx]$ ls
myTest  test.c
[gongruiyang@localhost ClassLinunx]$ pwd 
/home/gongruiyang/ClassLinunx                           <----当前路径
[gongruiyang@localhost ClassLinunx]$ myTest 
This is AKA giao, peace & love.                     	<----程序输出

But if we change a directory and execute again, the following result will appear, and the executable file myTest cannot be found.

[gongruiyang@localhost ClassLinunx]$ cd ..
[gongruiyang@localhost ~]$ myTest
bash: myTest: 没有那个文件或目录

In order to solve the matter from that directory can run the test executable program , we need to put it in the directory into the PATH environment variable to go

  • Increase of environment variable PATH

Goal: Put the /home/gongruiyang/ClassLinunx directory into the environment variable PATH, so that our test program can be executed anywhere

Use environment variable PATH increase command:

PATH="${PATH}:待添加目录"

There will be the following phenomena:

image.png

At this time, we have the directory containing the executable file myTest into the environment variable , the default search path to include the ClassLinux this folder, we try to run in a different directory myTest the executable file will not appear File Not Found case it

[gongruiyang@localhost TestDIR]$ pwd
/home/gongruiyang/TestDIR
[gongruiyang@localhost TestDIR]$ myTest 
This is AKA giao, peace & love.

Guess you like

Origin blog.csdn.net/weixin_45437022/article/details/109819582