Below is a function that implements two ways to retrieve all environment variables (both methods are cross-platform):
- using Java capabilities in MATLAB
- 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')