Set environment variables in task.json in vscode for WSL

Viewed 15333

I tried to set environment variables for my Visual Studio Code tasks that will run in my Windows Subsystem Linux. However, it does not seem to work. Here is my tasks.json:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "test env",
            "type": "shell",
            "command": "echo",
            "args": [
                "$test"
            ],
            "options": {
                "env": {
                    "test": "test_string"
                }
            }

        },
    ]
}

The output is:

> Executing task in folder ex12-test: echo $test <



Terminal will be reused by tasks, press any key to close it.

Note that by default shell has been manually modified to C:\WINDOWS\SysNative\bash.exefor WSL, as recommended here and here.

2 Answers

The options object goes outside of any task, so:

format
  "version": "2.0.0",
  "options": {
      "env": {
        "test": "test_string"
      }
   }
   "tasks": [
    {
        "label": "test env",
        "type": "shell",
        "command": "echo",
        "args": [
            "$env:test"
        ],
    },

And then access the options argsuments like so:

$env:test  or    ${env:test}
]

What I eventually did for my VS Code (v1.67.1) is:

  • Add my env variables into a settings.json
  • Use the traditional %ENV_VAR% option.

So in the settings.json, create this:

{
  "terminal.integrated.env.windows": { // switch to your os, check `Open Workspace Settings` in the Command Pallete then search for `environment`
    "AWS_REGION": "us-east-2", 
    "AWS_ID": "my_id"
  }
}

In the tasks.json, use the proper ENV variable reference:

"command": "echo %AWS_REGION%"

Related