Home  >  Q&A  >  body text

linux - 什么是环境变量?有什么作用?

环境变量问题 这是我的举例,到底什么是环境变量,有什么作用,在mac/linux系统上有什么区别?我查过一些资料,可是还是不太懂。在我学习node的过程中,经常有人跟我提到这个东西,可是我并不清楚它到底是什么。

怪我咯怪我咯2742 days ago801

reply all(2)I'll reply

  • 黄舟

    黄舟2017-04-17 13:57:12

    Environment variables simply set some parameters for the system and application. A specific environment variable includes

    1. Name

    2. Parameter value

    In this way, when the system starts an application, these parameters will be set by default. Under Linux, you can set the system global settings by modifying /etc/profile, ~/.profile and other files. Environment variables, such as:

    # other settings
    # ...
    export my_var 'hello world!';

    Then you can get this value while your program is running through the following code snippet

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

    Of course you can get environment variables in the nodejs program you mentioned like this:

    console.log(process.env)

    will output something like this:

    {
        PATH: '/usr/local/bin:/usr/bin',
        JAVAHOME: '/usr/lib/Java',
        ...
    }

    When executing a subprocess, you can also specify the subprocess's own environment variables, such as:

    var exec = require('child_process').exec;
    
    var child = exec('cat *.js', {
        PATH: '/usr/bin',
        MY_VAR: 'hello world!'
    }, function (error, stdout, stderr) {
        console.log('stdout: ' + stdout);
        console.log('stderr: ' + stderr);
        if (error !== null) {
          console.log('exec error: ' + error);
        }
    });

    Pass an Object through the second parameter of the child_process.exec function to override the default environment variable

    These are some of my understandings and insights. I hope they are helpful to you. I can’t go into more details, haha!

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 13:57:12

    Environment variables can be understood as a set of folder paths, but when you enter a command, the system automatically searches for executable programs in these folders in sequence, executes them if they are found, and reports an error if they are not found.

    Can you give me a reason for the student who downvoted it?

    reply
    0
  • Cancelreply