pattivacek
pattivacek

Reputation: 5823

List all environment variables in Matlab

How does one get a list of all defined environment variables in Matlab? I'm aware of getenv but you have to provide a name, and doc getenv offers no help in how to use it to retrieve items in any other way. I can't find any other relevant information online. Is this even possible?

I'm interested in a platform-independent answer (or at least Windows and Linux).

Upvotes: 12

Views: 14900

Answers (2)

Amro
Amro

Reputation: 124563

Below is a function that implements two ways to retrieve all environment variables (both methods are cross-platform):

  1. using Java capabilities in MATLAB
  2. using system-specific commands (as @sebastian suggested)

NOTE: As @Nzbuu explained in the comments, using Java's System.getenv() has a limitation in that it returns environment variables captured at the moment the MATLAB process starts. This means that any later changes made with setenv in the current session will not be reflected in the output of the Java method. The system-based method does not suffer from this.

getenvall.m

function [keys,vals] = getenvall(method)
    if nargin < 1, method = 'system'; end
    method = validatestring(method, {'java', 'system'});

    switch method
        case 'java'
            map = java.lang.System.getenv();  % returns a Java map
            keys = cell(map.keySet.toArray());
            vals = cell(map.values.toArray());
        case 'system'
            if ispc()
                %cmd = 'set "';  %HACK for hidden variables
                cmd = 'set';
            else
                cmd = 'env';
            end
            [~,out] = system(cmd);
            vars = regexp(strtrim(out), '^(.*)=(.*)$', ...
                'tokens', 'lineanchors', 'dotexceptnewline');
            vars = vertcat(vars{:});
            keys = vars(:,1);
            vals = vars(:,2);
    end

    % Windows environment variables are case-insensitive
    if ispc()
        keys = upper(keys);
    end

    % sort alphabetically
    [keys,ord] = sort(keys);
    vals = vals(ord);
end

Example:

% retrieve all environment variables and print them
[keys,vals] = getenvall();
cellfun(@(k,v) fprintf('%s=%s\n',k,v), keys, vals);

% for convenience, we can build a MATLAB map or a table
m = containers.Map(keys, vals);
t = table(keys, vals);

% access some variable by name
disp(m('OS'))   % similar to getenv('OS')

Upvotes: 5

sebastian
sebastian

Reputation: 9696

You could use

system('env')

on linux/mac, and

system('set') % hope I remember correctly, no windows at hand

In both cases you'd have to parse the output though, as it comes in the format variable=<variable-value>.

Upvotes: 11

Related Questions