Get the App
SLTechnology News&Howtos  ›  Servers  › 

The method of viewing and controlling environment variables under Linux

Shulou Source: shulou.com Published: 2022-06-02 01:33:03 10月04日 Update

View environment variabl

Look at a certain environment variable: for example, if we need to look at the environment variable HOME, we can type echo $HOME directly under shell, and we can print out the values of all environment variables and environment variables.

Print environment variabl

The global variable environ defined in libc points to the environment variable table, and environ is not included in any header file, so you should declare it with extern when using it.

Here is a program to print environment variables

The global variable environ defined in # include int main () {/ / libc points to the environment variable table, and environ is not included in any header file, so / / declare it with extern when you use it. Extern char** environ; / / while (environ) / / {/ / printf ("% s\ n", * environ++); / /} / / printf ("hah"); int I = 0; for (I = 0 NULL;i++ environ [I]! = NULL;i++) {printf ("% s\ n", environ [I]);} return 0;}

Control environment variable interface getenv,setenv,unsetenv

Getenv () function

# include char * getenv (const char * name)

The getenv () function searches the environment list to find the environment variable name and returns a pointer to the corresponding value string. Return NULL if it is not found

Setenv () function and unsetenv

# include int setenv (const char * name, const char * value, int overwrite); int unsetenv (const char * name)

Setenv () sets the environment variable, returns 0 if successful, and non-0 if not successful

Unsetenv () deletes an environment variable

Here is a program that you can test by yourself.

# include # include # include int main (void) {char* val; const char* name = "ABC"; / / get the value of the ABC environment variable val = getenv (name); printf ("No.1% slots% s\ n", name, val); / / override the write environment variable setenv (name, "I amsure of that I will get it", 1); printf ("No.2%s=%s\ n", name, val); val = getenv (name) Printf ("No.3%s=%s\ n", name, val); / / remove an environment variable int ret = unsetenv ("ABC"); printf ("ret =% d\ n", ret); val = getenv (name); printf ("No.3%s=%s\ n", name, val); return 0;}

The above is the whole content of this article, I hope it will be helpful to your study, and I also hope that you will support it.

Tags: Variables environment pointing success global function file program control content function name that is pointer interface learning help search support test Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Shulou Technology MySQL Apple macOS