Main Content

setenv

Set environment variable

Description

example

setenv(varname,varvalue) sets the values of operating system environment variables. If varname exists as an environment variable, then setenv replaces its current value with varvalue. If varname does not exist, then setenv creates an environment variable named varname and assigns varvalue to it.

setenv passes varname and varvalue to the operating system unchanged. Special characters, such as ;, /, :, $, and %, are unexpanded in varvalue.

A process launched using the MATLAB® system, unix, dos, or ! function reads the values assigned to variables using the setenv function.

setenv(varname) assigns a null value to varname. This syntax is equivalent to setenv(varname,""). On most UNIX® platforms, an environment variable can exist with an empty value (""). On the Microsoft® Windows® platform, this syntax is equivalent to removing the variable.

setenv(d) assigns all dictionary values to their associated environment variable names. (since R2023a)

Examples

collapse all

setenv("TEMP","C:\TEMP");
getenv("TEMP")
ans = 'C:\TEMP'
setenv("PATH",getenv("PATH") + ";D:\myfolder");

Create multiple environment variables, and then check that they exist.

setenv(["Var1" "Var2" "Var3" "Var4"],["Val1" "Val2" "Val3" "Val4"]);
isenv(["Var1" "Var2"; "Var3" "Var4"])
ans = 2x2 logical array

   1   1
   1   1

Remove two of the environment variables using unsetenv, and then check that they no longer exist.

unsetenv(["Var1" "Var4"]);
isenv(["Var1" "Var2"; "Var3" "Var4"])
ans = 2x2 logical array

   0   1
   1   0

You can also remove environment variables using setenv with missing. Change the value of one environment variable and remove another.

setenv(["Var2" "Var3"],["ValB" missing]);
isenv(["Var1" "Var2"; "Var3" "Var4"])
ans = 2x2 logical array

   0   1
   0   0

Input Arguments

collapse all

Environment variable names, specified as a string array, character vector, or cell array of character vectors.

The maximum number of characters in varname is 215 – 2, or 32,766. If varname contains the = character, then setenv throws an error. The behavior of environment variables with = in the name is not well defined.

Example: "PATH"

Environment variable values, specified as a string array, character vector, cell array of character vectors, or missing. Remove an environment variable by setting its value to missing.

Example: "C:\TEMP"

Environment variable names and values, specified as a dictionary. The specified dictionary can contain string arrays or cell arrays of character vectors.

Example: dictionary(["varname1","varname2"],["varvalue1","varvalue2"])

Example: dictionary({'varname1','varname2'},{'varvalue1','varvalue2'})

Extended Capabilities

Version History

Introduced before R2006a

expand all