Essential Skills for Linux Experts: A Comprehensive Guide to Environment Variables

Linux | Red Hat Certified | IT Technology | Operations Engineer
👇 Join the 1000-person technical communication QQ group. Note: [Public Account] for faster approval
Essential Skills for Linux Experts: A Comprehensive Guide to Environment Variables
1. Basic Concepts
Environment variables (environment variables) generally refer to parameters used to specify the operating environment of the operating system.
For example: when we write C/C++ code, we never know where the dynamic and static libraries we link to are located, but we can still link successfully and generate executable programs. The reason is that relevant environment variables help the compiler find them.
Environment variables usually have some special purposes and generally possess global characteristics in the system.
View the current environment variables in the Linux system:
Command:

Essential Skills for Linux Experts: A Comprehensive Guide to Environment Variables

Environment Variables on Windows:

Essential Skills for Linux Experts: A Comprehensive Guide to Environment Variables

Environment variables are essentially a type of variable, a K/V pairing relationship, consisting of variable names and variable values.
2. Common Environment Variables in Linux
1. View a Specific Environment Variable
echo $NAME #NAME: Environment Variable Name
For example:

Essential Skills for Linux Experts: A Comprehensive Guide to Environment Variables

2. PATH
Specifies the search path for commands.
1. When we write some C/C++ code and compile it into an executable program, running it with ./ essentially tells the operating system the location of the executable program.
2. However, system commands, which are also programs written in C, do not require a specified path. Why?
3. This is because the environment variable PATH stores the search paths for commands.

Essential Skills for Linux Experts: A Comprehensive Guide to Environment Variables

3. HOME
Specifies the user’s main working directory (the default directory when the user logs into the Linux system).
Every time we log into the system, the system records the logged-in user and fills in the HOME environment variable, creating a bash process to execute the command cd /home/XXX, entering our home directory. This is why we default to our home directory when entering the system.
Regular User:

Essential Skills for Linux Experts: A Comprehensive Guide to Environment Variables

Root User:

Essential Skills for Linux Experts: A Comprehensive Guide to Environment Variables

4. SHELL
The current shell, its value is usually /bin/bash.

Essential Skills for Linux Experts: A Comprehensive Guide to Environment Variables

3. Organization of Environment Variables
Each program receives an environment table, which is an array of character pointers. Each pointer points to an environment string ending with ‘
‘, and the last position of the table is NULL.
4. Adding Environment Variables
We just introduced the PATH environment variable, which specifies the search path for commands. Can we add the search path of our own executable programs to PATH so that our executable programs can also be executed directly without ./?
Test Code: test.c
#include <stdio.h>
#include <unistd.h>
int main(){
    int n = 3;
    while (n)    {
        printf("Genshin Impact Launch:%d\n", n);
        sleep(1);
        n--;
    }
}
Makefile:
ttest:test.c
gcc -o $@ $^
.PHONY:clean
clean:
    rm -rf ttest

Essential Skills for Linux Experts: A Comprehensive Guide to Environment Variables

Method 1:
Use export to import the path of our executable program into PATH, so that we can run the executable program directly without ./, as the operating system can find the executable program directly through the address in the environment variable.
export PATH=path

Essential Skills for Linux Experts: A Comprehensive Guide to Environment Variables

Note:
This will create an awkward situation where our PATH contains only this one path, meaning other paths from the previous TATH environment variable are overridden by the path we imported.
We can import environment variables like this:
export PATH=$PATH:path

Essential Skills for Linux Experts: A Comprehensive Guide to Environment Variables

Method 2:
Copy the executable program to the /usr/bin directory, which is the default path for system commands.
sudo cp ./ttest /usr/bin

Essential Skills for Linux Experts: A Comprehensive Guide to Environment Variables

Essentially, placing the executable program in the /usr/bin directory is the process of software installation.
The method of adding variables mentioned above adds commands to the system environment, while another way to add variables is to create local variables.
For example:
hello=100
This is how to add a local variable.
5. Inheritance of Environment Variables
1. Environment variables can be inherited by child processes.
2. The process imported using export can use the echo command to query. Echo is also a program, and the reason echo can query the imported bash environment variable is that echo inherits the bash environment variables.
3. However, only environment variables can be inherited by child processes; local variables cannot.
6. Accessing Environment Variables
1. Third Parameter of Command Line
Let’s first look at command line parameters:
#include <stdio.h>
int main(int argc, char *argv[]){
    int i = 0;
    for (i = 0; i < argc; i++)    {
        printf("%s ", argv[i]);
    }
    printf("\n");
    return 0;
}
Note: 1. argv is an array of pointers, each element is a char*, and each char* points to a string. 2. argc is the number of elements in the argv array.

Essential Skills for Linux Experts: A Comprehensive Guide to Environment Variables

 Note: 1. The argv array stores the strings input in the command line separated by spaces. 2. The order is from left to right.
Command line’s third parameter:
Test Code:
#include <stdio.h>
int main(int argc, char *argv[], char *env[]){
    int i = 0;
    for (; env[i]; i++)    {
        printf("%s\n", env[i]);
    }
    return 0;
}
Execution Result:

Essential Skills for Linux Experts: A Comprehensive Guide to Environment Variables

Note: 1. env is also an array of pointers, each array element stores an environment variable. 2. This proves that environment variables can be inherited by child processes. 3. This confirms the organization of environment variables.
2. Accessing via Third-party Variable environ
Test Code:
#include <stdio.h>
int main(int argc, char *argv[]){
    extern char **environ; // Environment variable table
    int i = 0;
    for (; environ[i]; i++)    {
        printf("%s\n", environ[i]);
    }
    return 0;
}
Execution Result:

Essential Skills for Linux Experts: A Comprehensive Guide to Environment Variables

 Note: The global variable environ defined in libc points to the environment variable table. Environ is not included in any header file, so it needs to be declared with extern when used.
3. Accessing or Setting Environment Variables via System Calls
System Call:
getenv()

Essential Skills for Linux Experts: A Comprehensive Guide to Environment Variables

getenv’s parameter is the environment variable name, and it returns the value string of the environment variable. If the corresponding environment variable is not found, it returns NULL.
Test Code:
[wq@iZuf6hzw565sb02fomef99Z 23_9_12]$ HELLO=100 # Local Variable
[wq@iZuf6hzw565sb02fomef99Z 23_9_12]$ export MYHELLO=100 # Environment Variable
#include <stdio.h>
#include <stdlib.h>
int main(){
    if (getenv("PATH"))    {
        printf("PATH:%s\n", getenv("PATH"));
    }
    if (getenv("MYHELLO"))    {
        printf("MYHELLO:%s\n", getenv("MYHELLO"));
    }
    if (getenv("HELLO"))    {
        printf("HELLO:%s\n", getenv("HELLO"));
    }
    return 0;
}
Essential Skills for Linux Experts: A Comprehensive Guide to Environment Variables
<span>Note:</span>
1. Environment variables usually have global properties and can be inherited by child processes. 2. We previously mentioned that local variables are not inherited by child processes, as shown in the code above. 3. However, why can we query local variables using the echo command? Because echo is a built-in command.
Essential Skills for Linux Experts: A Comprehensive Guide to Environment Variables
For course inquiries, add: HCIE666CCIE
↑ Or scan the QR code above ↑
If you have any technical points or content you want to see
You can leave a message below to let me know!

Leave a Comment