[Linux] Environment variables--PATH environment variables/environment variable operations/command line parameters

1. PATH environment variable

1.What is the PATH environment variable?

Here we first ask a question:Why do we need a path to run the program we wrote, but the system instructions do not need a path?

This is because the system can find its location. There are relevant environment variables in the system that save the search path of the program. The environment variable used to search for executable programs in the system is called PATH. So we only need to copy our program to the /usr/bin/ path (but we do not recommend it, the reason is explained below)

First we understand what environment variables are

Environment variables generally refer to some parameters used in the operating system to specify the operating environment of the operating system.

For example: when we write C/C++ code, when linking, we never know where our linked dynamic and static libraries are, but we can still link successfully and generate executable programs. The reason is that there are relevant environment variables to help compile search engine.

Environment variables usually have some special purpose, and they usually have global properties in the system.

So in fact, the various instructions in Linux are essentially executable programs in the /usr/bin directory, and they are no different from the executable programs we write ourselves. But when using a command, the system will automatically search for the command in PATH. If it is found, it will be executed. If not found, an error will be reported - "command not found". Therefore, various commands in Linux do not need to specify a path, and the programs we write ourselves Need to specify path

2. How to add PATH environment variable

We can use the following command to view the contents contained in the PATH environment variable:

echo $PATH

Insert image description here

What we need to note is that the different path separators in PATH are:

We can also add content to PATH so that our own programs can be executed without specifying a path.

Method 1:Add the program directly to the /usr/bin directory(This method is not recommended because the program we wrote Not tested and may pollute the command pool)

Insert image description here

We delete using the following command:

sudo rm /usr/bin/mycmd

Later, when we execute the program we wrote ourselves, we need to bring the path

Insert image description here

Method 2:Use the export command to import the path of the current executable program into PATH

export PATH=$PATH:当前路径

Insert image description here

【Notice】

$PATH represents the content in the previous PATH, and the newly added content after:, so we cannot directly use the following instructions:

export PATH=当前路径

Because this will overwrite the previous contents in PATH, so that various instructions in Linux must specify the directory before they can be executed, because the operating system cannot find the original instructions in the system in /usr/bin. At this time, we only need to re- Just log in, because environment variables are memory-level variables. Every time we log in to the shell, the environment variables will be recompiled and executed. At the same time, there cannot be spaces in PATH because spaces are used as delimiters in Linux.

Insert image description here

Those of us who have studied Java all know that we need to configure environment variables in Windows when we first learn. In fact, the essence is to add content to PATH (the path separator in Windows is a semicolon)

View environment variables under windows:

Settings->About->Advanced system settings->Environment variables

Insert image description here

3. Other environment variables in the system

The PATH environment variable is just one of the many environment variables in the system. In addition to PATH, we have many other environment variables. Different environment variables have different functions and are suitable for different scenarios.

PATH: Specify the search path for the command

HOME: Specify the user's home working directory (that is, the default directory when the user logs in to the Linux system)

SHELL: The current Shell, its value is usually /bin/bash

HOSTNAME: host name

USER: current username

PWD: current system path

HISTSIZE: The maximum number of historical commands that the shell can remember

Insert image description here

We can also use the env command to view all environment variables in the system:

Insert image description here

4. Sources of environment variables

We use the "ls - al /hone/hdp" command to find that there are two hidden files in the home directory – .bash_profile and .bashrc:

Insert image description here

Insert image description here

Insert image description here

In fact, when we log in to the shell, the operating system will let our current shell execute the contents of the .bash_profile file, and .bash_profile will call and execute .bashrc. They will import the corresponding environment variables into the context of the shell process. environment, so this explains why after we overwrite $PATH, we can log in to the shell again.

Definition of environment variables

Environment variables are a large number of global variables pre-set in the system by the operating system to meet different application scenarios. These variables often have special functions and can always be accessed by bash and bash sub-processes.

The fundamental reason why environment variables have global properties is that environment variables will be inherited by child processes.

2. Operation of environment variables

1. Set environment variables

Variables can be defined on the Linux command line, but the variables we define in this way are local variables, which are only valid in the bash process, not environment variables, because environment variables have global attributes.

Insert image description here

We can use export to directly define environment variables, or we can use it to turn existing local variables into environment variables.

Insert image description here

We can use the set command to view all variables, including environment variables and local variables, and use unset to cancel variables, including environment variables and local variables.

Insert image description here

2. Get environment variables through getenv

We can use echo $environment variable name to obtain specific environment variables, or we can obtain environment variables through the getenv() function:

Insert image description here

Where name is the name of the environment variable we need to obtain. If the acquisition is successful, the specific content of the environment variable will be returned. If it fails, NULL will be returned.

In this way, we can use the getenv() function to write certain instructions in the system, such as pwd:

#include <stdio.h>
#include <stdlib.h>
#define MYPWD "PWD"
int main()
{
    
    
    char* env = getenv(MYPWD);
    printf("%s\n",env);
    return 0;
}

Insert image description here

3. The meaning of environment variables

We know that environment variables are a large number of global variables pre-set in the system by the operating system to meet different application scenarios. Among them, PATH is to meet our instruction path search needs. In addition to instruction requirements, there are many other requirements. One of the most important ones is identity authentication

Let us illustrate with an example:

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

#define USER "USER"

int main()
{
    
    
    char* who = getenv(USER);
    if(strcmp(who,"root")==0)
    {
    
    
        printf("user:%s\n",who);
        printf("user:%s\n",who);
        printf("user:%s\n",who);
        printf("user:%s\n",who);
        printf("user:%s\n",who);
    }
    else
    {
    
    
        printf("权限不足\n");
    }
    
    return 0;
}

Insert image description here

We use su - instead of su here because su - will log in to the shell again. At this time, the shell will reload the environment variables and change $USER from hdp to root, while su just switches the user identity to root.

Insert image description here

We can obtain the current Linux user through the getenv function inside the program, then determine whether it has certain permissions, and then perform the corresponding operation.

In addition, we can also use stat to obtain other attributes of a file, such as read, write, execution, etc., and then use these attributes to determine whether a user can perform corresponding operations on the file.

Insert image description here

The stat command is a command used to display detailed information about a file or directory, including file size, creation time, modification time, access time, permissions, etc. In Linux and Unix operating systems, the stat command usually uses the following syntax:

stat [选项] 文件名

where the options can be one of the following:

  • -c: Specify custom format output.
  • -f: Specify the file system information output format.
  • -t: Specify time format output.

3. Command line parameters

We can get environment variables through the getenv function, and we can also get environment variables through named line parameters.

We know that the main function in C language has parameters, and these parameters can be passed through the command line:

int main(int argc,char* argv[],char* env);

where argc is an integer, representing the number of elements in the argv array. argv is an array of pointers. Each element in the array points to a string.

We can print the environment variables stored in the argv array. When adding options, the environment variables will also increase.

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

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

Insert image description here

When used together, they can achieve functions similar to the "ls -a -l -d" option. By passing different options, we can use different functions.

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

int main(int argc,char* argv[],char* env[])
{
    
    
    if(argc != 2)
    {
    
    
        printf("Usage: \n\t\%s [-a/-b/-c/-ab/-ac/-bc]\n",argv[0]);
    }
    if(strcmp("-a",argv[1]) == 0)
    {
    
    
        printf("功能a\n");
    }
    if(strcmp("-b",argv[1]) == 0)
    {
    
    
        printf("功能b\n");
    }
    if(strcmp("-c",argv[1]) == 0)
    {
    
    
        printf("功能c\n");
    }
    if(strcmp("-ab",argv[1]) == 0)
    {
    
    
        printf("功能ab\n");
    }
    if(strcmp("-ac",argv[1]) == 0)
    {
    
    
        printf("功能ac\n");
    }
    if(strcmp("-bc",argv[1]) == 0)
    {
    
    
        printf("功能bc\n");
    }
    
    return 0;
}

Insert image description here

The pointer array env is used to accept the parameters of the environment variables passed by the parent process. We can print the contents of env in the main function:

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

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

Insert image description here

The program can also obtain environment variables through the environment table environ - the environment variable table is an array of character pointers, each pointer points to an environment variable string ending with '\0', and each process will receive an environment variable table

Insert image description here

Insert image description here

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

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

Insert image description here

Guess you like

Origin blog.csdn.net/qq_67582098/article/details/134435620