Environment Variables in Scilab

Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables.

// To set a key/value pair, use setenv. To get a
// value for a key, use getenv. This will return
// an empty string if the key isn't present in the
// environment.
setenv('FOO', '1');
disp(['FOO: ', getenv('FOO')]);
disp(['BAR: ', getenv('BAR')]);

// Use lines(getenv()) to list all key/value pairs in the
// environment. This returns a matrix of strings in the
// form KEY=value. You can use strsplit to separate
// them into key and value. Here we print all the keys.
disp(' ');
env = lines(getenv());
for i = 1:size(env, 1)
    pair = strsplit(env(i), '=');
    disp(pair(1));
end

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is empty.

FOO: 1
BAR: 

The list of keys in the environment will depend on your particular machine.

TERM_PROGRAM
PATH
SHELL
...
FOO

If we set BAR in the environment first, the running program picks that value up.

$ BAR=2 scilab -nw -f environment-variables.sce
FOO: 1
BAR: 2
...

In Scilab, we use setenv to set environment variables and getenv to retrieve them. The lines(getenv()) function is used to get all environment variables as a matrix of strings. We then use a for loop and strsplit to separate and display the keys.

Note that in Scilab, we typically save our scripts with a .sce extension and run them using the scilab -nw -f command in the terminal, where -nw stands for “no window” (console mode) and -f is followed by the script filename.